This question asks why
a[5] == 5[a]
It is answered in all aspects except one...
Why is one allowed to put an array subscript after an integer in the first place? And why isn't one allowed to write something like
[a]5
or
[5]a
or put []
in some other odd place?
In other words, what is the definition of where an array index operator is allowed?
EDIT I: The answers I received that quote the the standard were a little hard to grasp at first. But with the help of the responders I now understand. An array subscript (a square bracket) is allowed after a pointer or an integer. If it follows a pointer, what's inside the brackets must be an integer. If it follows an integer, what's inside the brackets must be a pointer.
I'm accepting the less upvoted answer because he did a bit more hand-holding in getting me to understand the quote from the standard. But the answer that strictly quotes the standard is correct too. It was just harder to understand at first.
EDIT II: I do not think my question was a duplicate. My question was about the allowed grammar regarding the array subscript operator. It was answered by quotes from the standard that never appear in the question I supposedly duplicated. It is similar, yes, but not a duplicate.
Answer
Postfix expression grammar from the C11 standard:
postfix-expression:
primary-expression
postfix-expression [ expression ]
postfix-expression ( argument-expression-listopt )
postfix-expression . identifier
postfix-expression -> identifier
postfix-expression ++
postfix-expression --
( type-name ) { initializer-list }
( type-name ) { initializer-list , }
Primary expression grammar from the C11 standard:
primary-expression:
identifier
constant
string-literal
( expression )
generic-selection
And so on. 5 is an integer constant, so 5[a] match this:
postfix-expression [ expression ]
Hope this is what you mean.
EDIT: I forgot to mention this, but other comments already did:
One of the expressions shall have type ‘‘pointer to complete object type’’, the other
expression shall have integer type, and the result has type ‘‘type’’.
That 'integer type' it's needed to forbid non-sense floating-point constants subscripting.
No comments:
Post a Comment