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.
문제
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.
a[i]
is defined as *(a+i)
.
So 42[a]
=a[42];
and it is perfectly safe
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.