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++?
int& x
instead ofint &x
. The reasoning is usually because there's a stronger emphasis on types in C++, and so C++ developers often want to look atint*
as one indivisible thing -- a completely different data type fromint
with a different interface. Also helps to keep it uniform when you want to do likevector<int*>
as opposed tovector<int *>
.int *x
- what's the int? *x. C++:int* x
- what's x? an int*.int* x, y
defined two pointers instead of one pointer and one integer. That's really confusing when you want to think ofint*
as like an indivisible thing. That said, I got used to a coding standard where it was forbidden to define more than one variable per line.T *ptr;
reflects how the grammar actually works - the*
is part of the declarator, not the type specifier. It’s the same reason we don’t writeT[N] array;
orT() func
. Pointer-ness, array-ness, and function-ness are specified in the declarator. You can writeT* p
orT *p
orT * p
or evenT*p
- they will all be parsed asT (*p)
.T (*ap)[N]
,T (*fp)(...)
,T (*afp())[M]
, etc. Think about the prototype for the signal function, and how you would apply theT*
convention to it cleanly (it would require at least onetypedef
, which, IMO, obscures more than it clarifies).