Type Declaration - Pointer Asterisk Position

后端 未结 5 1074
失恋的感觉
失恋的感觉 2020-12-23 17:21

in C++, the following means \"allocate memory for an int pointer\":

int* number;

So, the asterisk is part of the variable type; without it,

5条回答
  •  鱼传尺愫
    2020-12-23 17:48

    Actually the asterisk is attached to the variable (a convention inherited from C), so

    int * number1, number2;
    

    declares number1 as a pointer to int (i.e. *number1 is an int), and number2 as an int.

    The spacing has no effect on how the number's are typed. It just serves as a token separator. All of the following are the same to compiler, because the spaces will be stripped after parsing.

    int *a;
    int*a;
    int* a;
    int * a;
    int/**a***/*/*a***/a;
    

    Use

    int* number1, *number2;
    

    to create two pointers, or even better, split it into multiple declarations to avoid confusion.

    int* number1;
    int* number2;
    

提交回复
热议问题