C declarations
Morris M. Keesan
keesan at bbncca.ARPA
Wed Jan 30 02:31:48 AEST 1985
-------------------------------
>From: Fred <jfn%vanderbilt.csnet at csnet-relay.arpa>
>Subject: C declarations
> I have a question about C declarations. The [] notation is equivalent
>to the * notation, right? We have
> int ptr[] <=> int *ptr
>and
> int *ptr[] <=> int **ptr
> The question concerns the [] syntax, which takes on a different meaning if
>data initialization occurs. For example:
> int ptr[]; declares one pointer
>but
> int ptr[] = { 1, 2, 3 }; declares a three element int array.
> Is this a desirable characteristic of C? Could someone please comment on
>the precise meaning of [] in declarations.
Sigh. This is something we cover in this newsgroup/list at least twice a year.
[] and * are NOT the same. A few citations from the C Reference Manual (CRM),
as printed in "The C Programming Language", by Kernighan & Ritchie (K&R):
CRM section 8.4, K&R pp. 194-5:
Now imagine a declaration T D1 where T is a type-specifier (like int,
etc.) and D1 is a declarator. . . . If D1 has the form
D[constant-expression] or D[] then the contained identifier has type "...
array of T". [Ed. note: NOT "pointer to T".] . . . When several "array of"
specifications are adjacent . . . the constant expressions . . . may be
missing only for the first member of the sequence. This elision is useful
when the array is external and the actual definition, which allocates
storage, is given elsewhere. The first constant-expression may also be
omitted when the declarator is followed by initialization. In this case the
size is calculated from the number of initial elements supplied.
CRM section 10.1, K&R p. 205, "External function definitions":
. . . since a reference to an array . . . is taken to mean a pointer to
the first element of the array, declarations of formal parameters declared
"array of ..." are adjusted to read "pointer to ...".
So in the examples above, the declarations declare:
int *ptr[]; /* ptr is a pointer to an array of int */
int ptr[]; /* ptr is an array of int, of unspecified size */
int ptr[] = { 1, 2, 3 }; /* ptr is an array of three ints */
The ONLY time (repeat ONLY) when [] is equivalent to * is in the declaration of
formal parameters to a function. E.g.
f(ptr) int ptr[]; { . . . }
is indeed equivalent to
f(ptr) int *ptr; { . . . }
In retrospect, considering the confusion this has caused through the years, I
think it was probably a mistake to allow this equivalence.
--
Morris M. Keesan
{decvax,linus,ihnp4,wivax,wjh12,ima}!bbncca!keesan
keesan @ BBN-UNIX.ARPA
More information about the Comp.lang.c
mailing list