A have found the following snippet:
int a[100];
...
int value = 42[a];
Which appears to do exactly what a[42]
does.
Is it a bogus with undefined behavior or a perfectly legal C++ code?
A have found the following snippet:
int a[100];
...
int value = 42[a];
Which appears to do exactly what a[42]
does.
Is it a bogus with undefined behavior or a perfectly legal C++ code?
It's perfectly legal. With pointer arithmetic, a[42]
is equivalent to *(a + 42)
, which (addition being commutative) is equivalent to *(42+ a)
, which (by definition of []
) is equivalent to 42[a]
.
So it's obscure, but well-defined.
The array operator is commutative.
a[n] == *(a + n) == *(n + a) == n[a]
And it's perfectly legal.
42[a]
is exactly equivalent to a[42]
, and entirely legal. It works because a pointer address is just an integer underneath, so you can do the arithmetic either way round (an array variable is really just a pointer in a thin disguise).
It's not usually a good idea for readability though, unless you're deliberately trying to obfuscate the code.