Home >Backend Development >C++ >Why Does `2[arr]` Work in C and C ?
Accessing Arrays by Index[array] in C and C
The classic interview question involving the unconventional array access syntax 2[arr] has generated curiosity among programmers. This syntax, which assigns a value to the third element of the array, appears unusual due to the flipped order of the array name and the index.
According to the C/C specifications, this unorthodox approach is indeed valid. The C99 standard's 6.5.2.1 paragraph 1 explicitly states that the arguments to the [] operator include an expression of type "pointer to object type" and an integer expression.
Furthermore, paragraph 2 clarifies that the definition of the [] operator is identical to (*((E1) (E2))), where E1 represents the array object (or a pointer to its first element) and E2 represents the integer index. While this definition outlines the functionality of the operator, it doesn't impose any restrictions on the order of the arguments.
This means that expressions like 2[arr], where the index precedes the array name, are syntactically valid and semantically correct. The expression is evaluated as *(2 arr), with 2 being added to the base address of the array. Consequently, the third element of the array is successfully targeted and modified.
Therefore, the reversed syntax of 2[arr] is not merely a compiler trick but a legitimate feature of C and C languages, allowing programmers to access array elements in a non-traditional but fully functional manner.
The above is the detailed content of Why Does `2[arr]` Work in C and C ?. For more information, please follow other related articles on the PHP Chinese website!