Why is 5 [a] valid and does not generate an invalid identifier error?

Q With arrays, why is this so, [5] == 5 [a]? it is explained that the operator [] in a[5] is defined as *(a + 5) , and since + is commutative, 5[a] means *(5 + a) , and therefore the two expressions refer to the same memory location . Good.

However, C also defines in 6.4.2.1 that an identifier cannot begin with a digit. In 5[a] identifier of array 5 , which is not a valid identifier. Why does 5[a] not generate an invalid identifier error?

+5
source share
1 answer

5 not an identifier; it is an integer literal.

Standard C literally states that 5[a] is just syntactic sugar, which should be equivalent to *(5 + a) . In C, there is no requirement that the first operand of the + operator be an identifier, so the code works very well.

6.5.6, my emphasis is:

To add, both operands must be of arithmetic type, or one operand must be a pointer to the full type of the object, and the other must have an integer type .

+10
source

Source: https://habr.com/ru/post/1237927/


All Articles