5

Both of the following are valid pointer declarations in C/C++:

int *x;
int* x;

The former seems to be preferred by seasoned C/C++ programmers. I personally find the latter to be easier to understand - it illustrates that pointer-ness is a factor of the variable's type, not its name. Furthermore, this unifies stylistically the declaration of pointers and functions returning pointers:

int* foo(); //foo returns an int*
int* x;     //x is an int*
int *foo(); //generally unused (in my experience)
int *x;     //feels wrong in this context

int *x seems counter-intuitive despite being the norm, so I feel I must be overlooking something.

What motivates syntactic preference regarding pointer declaration in C/C++?

Conduit
  • 159

1 Answers1

5

Both forms have exactly the same syntax. They differ only by spacing arrangements.

The first form is preferred because it reflects well the semantic: the pointer is only for the variable that immediately follows the star:

int *p, a; // p is pointer, a is plain int

The second form could be misleading, because it gives the impression that the pointer belongs to the type and would be applicable for all the variables in the same statement:

int* p, a; // still, only p is pointer, a is plain int despite impressions
Christophe
  • 81,699