How do I deduce from the C++ Standard that an array [] has higher precedence than a pointer?
Asked Answered
H

1

7

I know that a declaration like

int* a[5];

declares a as an array of 5 pointers to int. But how do I deduce this, just by using the C++ Standard?

Holub answered 25/4, 2021 at 20:29 Comment(2)
a is basically a pointer to an array of 5 int pointers.Milo
@ZeeshanArif, that isn't the question; also, a is an array in this context, not a pointer to one.Pleading
H
5

Just see the grammar of C++.

ptr-declarator:
    noptr-declarator
    ptr-operator ptr-declarator
noptr-declarator:
    declarator-id attribute-specifier-seqopt
    noptr-declarator parameters-and-qualifiers
    noptr-declarator [ constant-expressionopt] attribute-specifier-seqopt
    ( ptr-declarator )

and

ptr-operator:
    * attribute-specifier-seqopt cv-qualifier-seqopt
    & attribute-specifier-seqopt
    && attribute-specifier-seqopt
    nested-name-specifier * attribute-specifier-seqopt cv-qualifier-seqopt

Thus this declaration

int* a[5];

may be written like

int ( * ( ( a )[5] ) );

That is ( ( a )[5] ) is a noptr-declarator and ( * ( ( a )[5] ) ) is ptr-operator ptr-declarator.

A declaration of a pointer to an array of 5 integers will look like

int ( *a )[5];
Hagiarchy answered 25/4, 2021 at 20:34 Comment(3)
I cannot understand how a grammar production could determine a precedence of operators in C or C++.Holub
@Holub As it is seen from the grammar a declarator can consist of two parts ptr-operator ptr-declarator. So at first the ptr-declarator is built and then the ptr-operator is applied.Hagiarchy
@PatrickRoberts Yes, I used the wrong terminology, but I think you understood what I meant.Holub

© 2022 - 2024 — McMap. All rights reserved.