Home >Backend Development >C++ >Is `index[array]` a Valid Array Access Syntax in C and C ?

Is `index[array]` a Valid Array Access Syntax in C and C ?

Susan Sarandon
Susan SarandonOriginal
2024-11-24 21:55:18290browse

Is `index[array]` a Valid Array Access Syntax in C and C  ?

Accessing Arrays by Index[array] in C and C

While the typical form of array indexing is array[index], C and C provide an alternative syntax: index[array]. This syntax has puzzled many programmers, but is it valid by the language specifications?

Question:

int arr[] = {1, 2, 3};
2[arr] = 5; // Does this compile?
assert(arr[2] == 5); // Does this assertion fail?

Explanation:

This trick question relies on the commutative nature of addition. The operation index[array] is converted to *(index array), and since addition is commutative, we might assume that 2[arr] and arr[2] are equivalent. However, this is not explicitly stated in the language specifications.

Answer:

Yes, the code is valid according to the C and C specifications.

C99 (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".

C99 (6.5.2.1, paragraph 2):

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).

These specifications do not require the order of the arguments to [] to be sane. Therefore, both lines in the code compile and execute as expected, and the assertion passes.

The above is the detailed content of Is `index[array]` a Valid Array Access Syntax in C and C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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