I was hoping someone could enlighten me as to the following, seemingly, curious syntax. I would like to understand its potential usefulness or the mechanism that makes the syntax valid.
If you have
char A[] {'a', 'b', 'c'};
then 2[A] == 'c'
.
Q1: Is this effect stemming from the parsing rules for expressions that involve access to elements of multi-dimensional built-in arrays? E.g., B[ i ][ j ][ k ].
Q2: What is the rationale behind
int A[][2] {{1, 2}, {3, 4}};
being valid, but
int A[][] {{1, 2}, {3, 4}};
being not? (the error reads Array has incomplete element type 'int[]'
)
Thanks in advance.
I would like to understand its potential usefulness
It has no use, apart from obfuscation. It's just a quirk of the way []
is defined.
the mechanism that makes the syntax valid
a[b]
is defined to be equivalent to *(a+b)
. Since addition is commutative, this is equivalent to *(b+a)
, and hence to b[a]
.
int A[][] {{1, 2}, {3, 4}};
In order to declare an array, the element type must be complete; that is, it must have been fully defined, so that the compiler knows its size. Otherwise, the compiler can't know how the elements are arranged in memory, so can't generate the pointer arithmetic needed to access them. The size of the array itself can be left unspecified, since that's not needed to access the elements.
A multi-dimensional array is an array of arrays, and the same rule applies: while the size of the outer array can be left unspecified, the inner array type must be complete. For an array type to be complete, its size must be specified.