Home > Backend Development > C++ > Does `2[arr]` Equal `arr[2]` in C and C : A Commutative Array Access?

Does `2[arr]` Equal `arr[2]` in C and C : A Commutative Array Access?

Susan Sarandon
Release: 2024-11-25 14:42:11
Original
797 people have browsed it

Does `2[arr]` Equal `arr[2]` in C and C  : A Commutative Array Access?

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?
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template