I cant use something like this:
int n[];
I get an error:
incomplete type "int []" is not allowed
But I can use this:
int n [] = {1,2,3};
And I don't get any errors.
1)Does it turn out that the second example is no longer an incomplete type?
2)Then why can't we use arrays of incomplete types?
For example: int n[][] = {{1,2},{3,4}};
If the second example is no longer an incomplete type during initialization, then the array elements that are arrays and elements of an incomplete type are also not incomplete types and we can use something like this.
Thank you in advance.
1)Does it turn out that the second example is no longer an incomplete type?
This is because the C standard says the compiler determines the array dimension by examining the initializers. C 2024 6.7.11:
… If an array of unknown size is initialized, its size is determined by the largest indexed element with an explicit initializer. The array type is completed at the end of its initializer list…
2)Then why can't we use arrays of incomplete types?
For example: int n[][] = {{1,2},{3,4}};
This is because the element type must be complete when the array declarator is analyzed while processing the C grammar. Effectively, when the compiler sees the =
in int n[] = …
or int n[][] = …
, the element type of each array must be complete.
That is fine in int n[] = …
, because its element type is int
, which is complete.
It is a problem in int n[][] = …
, because the element type of the outer array is int n[]
, which is incomplete.
This violates a rule in C 2024 6.7.7.3:
… The element type shall not be an incomplete or function type…
That rule applies at the moment the array declarator is processed; the fact that the size might be inferred later from initializers does not save it.
Now, maybe you could change the C standard to have the compiler infer all array dimensions from the list of initializers. However:
int n[][2] = { 1, 2, 3, 4 };
to have the same effect as int n[][2] = { { 1, 2 }, { 3, 4 } };
. The former would not work with n[][]
.)