curtw@hpcllca.HP.COM (Curt Wohlgemuth) (01/14/89)
I have a question on ANSI C declaration semantics. Here is a code snippet: ......... (file scope) int a[5]; int a[] = {1, 2, 3}; ......... (end of snippet) Are these declarations an invalid combination? (I.e., is this non-conforming?) And if these are valid, how about reversing them? ......... (file scope) int a[] = {1, 2, 3}; int a[5]; ......... (end of snippet) As you can probably tell, I'm interested in just where the size of the empty-bracketed "a" is to be "filled in". Before the '=', or at the end of the initializer? Any and all comments would be appreciated. Thanks, Curt Wohlgemuth
gwyn@smoke.BRL.MIL (Doug Gwyn ) (01/14/89)
In article <16490010@hpcllca.HP.COM> curtw@hpcllca.HP.COM (Curt Wohlgemuth) writes: >......... (file scope) >int a[5]; >int a[] = {1, 2, 3}; >Are these declarations an invalid combination? No, the declaration with initializer constitutes the external definition (the earlier one without initializer was a tentative definition). The array has five elements, as specified by the first declaration (the last two elements are initially 0, since they were not explicitly initialized). >......... (file scope) >int a[] = {1, 2, 3}; >int a[5]; This is illegal. After the first declaration, the array has three elements, and the second declaration contradicts this. The first declaration constitutes an external definition of a complete type. (Although at the "[]" the type is incomplete, at the end of the initializer list the type becomes complete.) In contrast, consider int a[]; int a[5] = {1, 2, 3}; which produces an array with five elements. >As you can probably tell, I'm interested in just where the size of the >empty-bracketed "a" is to be "filled in". Before the '=', or at the end >of the initializer? I don't understand how you're thinking about this. The identifier either has complete type or not; once an initializer list has been processed the type is complete (the size is fixed at that point). The initializer for an incomplete array type sets the size according to the number of initializing elements provided. The initializer for an already complete but tentatively defined type (i.e. one without initializer in the earlier declaration) can contain any number of elements not to exceed the already declared size. Elements not explicitly initialized start out with 0 value.