Search code examples
arrayscsyntax

Where can I put an array subscript?


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?

NOTE: 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.


Solution

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