I, very occasionally, make use of multidimensional arrays, and got curious what the standard says (C11 and/or C++11) about the behavior of indexing with less "dimensions" than the one declared for the array.
Given:
int a[2][2][2] = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}};
Does the standard says what type a[1]
is, or a[0][1]
, is it legal, and whether it should properly index sub-arrays as expected?
auto& b = a[1];
std::cout << b[1][1];
m[1]
is just of type int[2][2]
. Likewise m[0][1]
is just int[2]
. And yes, indexing as sub-arrays works the way you think it does.
Does the standard define the type for
a[i]
wherea
isT [M][N]
?
Of course. The standard basically defines the types of all expressions, and if it does not, it would be a defect report. But I guess you are more interested on what that type might be...
While the standard may not explicitly mention your case, the rules are stated and are simple, given an array a
of N
elements of type T
, the expression a[0]
is an lvalue expression of type T
. In the variable declaration int a[2][2]
the type of a
is array of 2 elements of type array of two elements of type int
, which applying the rule above means that a[0]
is lvalue to an array of 2 elements, or as you would have to type it in a program: int (&)[2]
. Adding extra dimensions does not affect the mechanism.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With