Home > Article > Backend Development > Does `2[arr]` Work in C and C ?
Accessing Arrays Using Index[array] in C and C
Consider the following code snippet:
int arr[] = {1, 2, 3}; 2[arr] = 5; // Does this compile? assert(arr[2] == 5); // Does this assertion fail?
Some interviewers might ask why this code snippet compiles and executes without errors.
Understanding the Code
The expression 2[arr] is equivalent to *(2 arr). Since addition is commutative in C and C , the order of the arguments to [] does not matter. Therefore, 2[arr] effectively accesses the third element of the array arr.
Is This Guaranteed by the Language Specification?
Yes. The C and C standards explicitly state this behavior:
Therefore, accessing arrays using index[array] is guaranteed by the language specification, even if it seems unusual or counter-intuitive.
The above is the detailed content of Does `2[arr]` Work in C and C ?. For more information, please follow other related articles on the PHP Chinese website!