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

后端 未结 7 550
南方客
南方客 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 17:04

    The * modifies the variable name, not the type specifier. This is mostly because of the way the * is parsed. Take these statements:

    char*  x;
    char  *x;
    

    Those statements are equivalent. The * operator needs to be between the type specifier and the variable name (it is treated like an infix operator), but it can go on either side of the space. Given this, the declaration

    int*  a, b;
    

    would not make b a pointer, because there is no * adjacent to it. The * only operates on the objects on either side of it.

    Also, think about it this way: when you write the declaration int x;, you are indicating that x is an integer. If y is a pointer to an integer, then *y is an integer. When you write int *y;, you are indicating that *y is an integer (which is what you want). In the statement char a, *b, ***c;, you are indicating that the variable a, the dereferenced value of b, and the triply-dereferenced value of c are all of type char. Declaring variables in this way makes the usage of the star operator (nearly) consistent with dereferencing.

    I agree that it would almost make more sense for it to be the other way around. To avoid this trap, I made myself a rule always to declare pointers on a line by themselves.

提交回复
热议问题