Prof Russel Winder,
> > In C (and other languages) arrays can be initialised using a
> > list of numbers:
> >
> > int a_1[10] = { 3, 3, 3, 3, 3, 3, 3, 3};
>
>.... However, most
>people sidestep the issue by not over specifying -- which is what is
>being done here: there is a conflict between specifying the length of
>the array and providing an initializer.
It is true that most people omit the size specification if they can.
This is not a case of over specification, it is a case of introducing
redundant information which can be use to provide a consistency check.
In practice the code would look like:
#define MAX_WIDGETS 10
int a_1[MAX_WIDGETS] = { ...
where MAX_WIDGETS would occur in loops etc.
> Excluding the "lazy" case of
>initializing the first few of a larger array, most people would specify
>either the size and not initialize of the initializer and not the size
Agreed. But what is saved? The time taken to type 11 characters.
But to paraphrase that well known quote on the taste of certain newspaper
readers, "never underestimate the laziness of programmers".
The time saved in those cases where the array size information is available
and allows tools to pick up on the inconsistency probably runs into days of
effort over a major projects lifetime.
Unfortunately old habits are hard to change (and there are times where it may
difficult/awkward/inappropriate to provide a size). Hence the belt and braces
approach of a coding guideline requiring a size be given and a yet to be
written
guideline specifying how to lay the values out.
>-- the compiler does not use the size after allocating the storage. So:
>
> int a_1[] = { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } ;
>
>or
>
> int *const a_1 = { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } ;
The last case is not conforming C (a pointer must be initialised by a
scalar). Using constructs new in C99 you could say:
int * a_1 = &(int [10]){ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 } ;
>are the most likely occurrences of this sort of initialization. The
>size is then determined at compile time using the classic idiom:
>
> const int size = sizeof(a_1) / sizeof(int) ;
Ha, your showing your C++ background here. The object size is not
a constant in C, it is a const-qualified object (the difference is that
it cannot occur where a constant expression can occur).
derek
--
Derek M Jones tel: +44 (0)
1252 520 667
Knowledge Software
Ltd mailto:[EMAIL PROTECTED]
Applications Standards Conformance Testing http://www.knosof.co.uk
- Automatic footer for [EMAIL PROTECTED] ----------------------------------
To unsubscribe from this list, mail [EMAIL PROTECTED] unsubscribe discuss
To join the announcements list, mail [EMAIL PROTECTED] subscribe announce
To receive a help file, mail [EMAIL PROTECTED] help
This list is archived at http://www.mail-archive.com/discuss%40ppig.org/
If you have any problems or questions, please mail [EMAIL PROTECTED]