Accessing Arrays by Index [Array] in C and C : A Commutative Curiosity
The enigmatic question that perplexes interviewers asks:
int arr[] = {1, 2, 3}; 2[arr] = 5; // Compiles? assert(arr[2] == 5); // Fails?
Intuition suggests that a[b] is translated to *(a b) and, since addition is commutative, 2[arr] should equate to *(2 arr).
Does the Standard Back This Up?
Indeed, the C and C standards endorse this behavior.
C Standard (C99):
Section 6.5.2.1, paragraph 1:
One of the expressions shall have type "pointer to object type", the other expression shall have integer type, and the result has type "type".
Paragraph 2 (emphasis added):
A postfix expression followed by an expression in square brackets [] is a subscripted designation of an element of an array object. The definition of the subscript operator [] is that E1[E2] is identical to (*((E1) (E2))). Because of the conversion rules that apply to the binary operator, if E1 is an array object (equivalently, a pointer to the initial element of an array object) and E2 is an integer, E1[E2] designates the E2-th element of E1 (counting from zero).
Conclusion
The standard unequivocally states that E1[E2] is equivalent to *(E1 E2), regardless of the order of the arguments. Therefore, 2[arr] yields the same result as arr[2], allowing both the assignment and assertion to succeed without raising eyebrows.
The above is the detailed content of Does `2[arr]` Equal `arr[2]` in C and C : A Commutative Array Access?. For more information, please follow other related articles on the PHP Chinese website!