Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In With arrays, why is it the case that a[5] == 5[a]? it is explained that the [] operator in a[5] is defined as *(a + 5) and because + is commutative, 5[a] means *(5 + a) and so the two expressions refer to the same memory location. Fine.

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

like image 758
Paul Ogilvie Avatar asked Dec 11 '15 12:12

Paul Ogilvie


1 Answers

5 is not an identifier, it is an integer literal.

The C standard literally state that 5[a] is just syntactic sugar that must be equivalent with *(5 + a). There is no requirement in C that the first operand of the + operator is an identifier, so the code works just fine.

6.5.6, emphasis mine:

For addition, either both operands shall have arithmetic type, or one operand shall be a pointer to a complete object type and the other shall have integer type.

like image 199
Lundin Avatar answered Oct 04 '22 02:10

Lundin