Accessing Arrays by Index[array] in C and C
In a knowledge test sometimes posed by interviewers, the following code is presented:
int arr[] = {1, 2, 3}; 2[arr] = 5; // does this line compile? assert(arr[2] == 5); // does this assertion fail?
It might initially appear that the expression 2[arr] should fail to compile, as it seems to be attempting to index an array using an integer as the array name. However, this unexpected syntax is indeed valid in both C and C .
To understand why, let's delve into the technicalities of the [] operator in these languages.
C and C Array Access Semantics
According to the C99 standard (6.5.2.1 paragraph 1), the [] operator expects arguments in the form:
Further, paragraph 2 of the same section explains that E1[E2] is equivalent to (*((E1) (E2))). This indicates that the expression E1[E2] can be interpreted as a pointer manipulation:
Crucially, there is no requirement within the standard that the order of arguments to [] be sane. Therefore, the expression 2[arr] is treated as equivalent to (*((2) (arr))).
Therefore, both the assignment and the subsequent assertion succeed, as expected.
The above is the detailed content of Does 2[arr] = 5 Compile and Pass Assertion in C and C ?. For more information, please follow other related articles on the PHP Chinese website!