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.In general
2[a]
is identical toa[2]
and this is guaranteed to be equivalent in both C and C++ (assuming no operator overloading), because as you meantioned it translates into*(2+a)
or*(a+2)
, respectively. Because the plus operator is commutative, the two forms are equivalent.Although the forms are equivalent, please for the sake of all that's holy (and future maintenance programmers), prefer the "a[2]" form over the other.
P.S., If you do get asked this at an interview, please do exact revenge on behalf of the C/C++ community and make sure that you ask the interviewer to list all trigraph sequences as a precondition to you giving your answer. Perhaps this will disenchant him/her from asking such (worthless, with regard to actually programming anything) questions in the future. In the odd event that the interviewer actually knows all nine of the trigraph sequences, you can always make another attempt to stomp them with a question about the destruction order of virtual base classes - a question that is just as mind bogglingly irrelevant for everyday programming.