There is this little trick question that some interviewers like to ask for whatever reason:
int arr[] = {1, 2, 3};
2[arr] = 5; // does this line compile?
assert(arr[2] == 5); // does this assertion fail?
From what I can understand, a[b]
gets converted to *(a + b)
and since addition is commutative, it doesn't really matter their order, so 2[a]
is really *(2 + a)
and that works fine.
Is this guaranteed to work by C and/or C++'s specs?
Yes. 6.5.2.1 paragraph 1 (C99 standard) describes the arguments to the
[]
operator:6.5.2.1 paragraph 2 (emphasis added):
It says nothing requiring the order of the arguments to
[]
to be sane.