Pointer syntax in C: why does * only apply to the first variable?

后端 未结 7 580
南方客
南方客 2020-12-09 16:30

The following declaration in C:

int* a, b;

will declare a as type int* and b as type int

7条回答
  •  眼角桃花
    2020-12-09 16:45

    C declarations were written this way so that "declaration mirrors use". This is why you declare arrays like this:

    int a[10];
    

    Were you to instead have the rule you propose, where it is always

    type identifier, identifier, identifier, ... ;
    

    ...then arrays would logically have to be declared like this:

    int[10] a;
    

    which is fine, but doesn't mirror how you use a. Note that this holds for functions, too - we declare functions like this:

    void foo(int a, char *b);
    

    rather than

    void(int a, char* b) foo;
    

    In general, the "declaration mirrors use" rule means that you only have to remember one set of associativity rules, which apply to both operators like *, [] and () when you're using the value, and the corresponding tokens in declarators like *, [] and ().


    After some further thought, I think it's also worth pointing out that spelling "pointer to int" as "int*" is only a consequence of "declaration mirrors use" anyway. If you were going to use another style of declaration, it would probably make more sense to spell "pointer to int" as "&int", or something completely different like "@int".

提交回复
热议问题