Operator precedence in C Definitions

心不动则不痛 提交于 2019-12-12 11:38:12

问题


Wikipedia claims that the [] operator precedes the * operator in evaluation.

Then, why does the following statement:

char *a[3];

declare an array of 3 character pointers, rather than a pointer to an array of 3 characters as per the operator precedence?


回答1:


Because, as Wikipedia says, [] has higher precedence than *?

Processing the declaration, the a[3] is processed as 'array of 3' before you process the *.

To declare a pointer to an array of three characters, you have to use parentheses to override the default precedence:

char (*a)[3];

Now the parentheses take precedence over the array.




回答2:


Here's the grammar for a declarator as taken from the standard (§ 6.7.5):

declarator:
    pointeropt direct-declarator

direct-declarator:
    identifier
    ( declarator )
    direct-declarator [ type-qualifier-listopt assignment-expressionopt ]
    direct-declarator [ static type-qualifier-listopt assignment-expression ]
    direct-declarator [ type-qualifier-list static assignment-expression ]
    direct-declarator [ type-qualifier-listopt * ]
    direct-declarator ( parameter-type-list )
    direct-declarator ( identifier-listopt )

pointer:
    * type-qualifier-listopt
    * type-qualifier-listopt pointer

type-qualifier-list:
    type-qualifier
    type-qualifier-list type-qualifier

parameter-type-list:
    parameter-list
    parameter-list , ...

parameter-list:
    parameter-declaration
    parameter-list , parameter-declaration

parameter-declaration:
    declaration-specifiers declarator
    declaration-specifiers abstract-declaratoropt

identifier-list:
    identifier
    identifier-list , identifier

As you can see, both [] and () bind to the declarator before *. Take the declaration

int *a[N];

The declarator is *a[N], which fits the pointeropt direct-declarator pattern above, and is thus parsed as *(a[N]), so a is an N-element array of pointer.

To sum up:

T *a[N]      -- declares an N-element array of pointer to T
T (*a)[N]    -- declares a pointer to an N-element array of T
T *f()       -- declares a function returning pointer to T
T (*f)()     -- declares a pointer to a function returning T  



回答3:


I'm confused about the question - the interpretation of the declaration matches the operator precedence. If you want a pointer to an an array you have to use parens to 'bind the * to the indentifier' before the [] binding.

char (*a)[3];


来源:https://stackoverflow.com/questions/4769972/operator-precedence-in-c-definitions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!