Bjarne Stroustrup says:
A typical C programmer
writes int *p
; and explains it *p is what is the int
emphasizing syntax, and may point to the C (and C++) declaration grammar to argue for the correctness of the style. Indeed, the * binds to the name p in the grammar.
A typical C++ programmer
writes int* p;
and explains it p is a pointer to an int
emphasizing type. Indeed the type of p is int*. I clearly prefer that emphasis and see it as important for using the more advanced parts of C++ well.
When declaring a pointer variable or argument, you may place the asterisk (or ampersand) adjacent to either the type or to the variable name.
The most important thing is to do this consistently within a single file.
// These are fine, space preceding.
char *c;
const int &i;
// These are fine, space following.
char* c;
const int& i;
int& i
separates names and types better thanint &i
. See the articles on isocpp.org, Herb Sutters or scott Meyers for examples.int& i
as good style, but due to its legacy C compatibility that 'good style' directly cloaks the actual semantics of your code...int *i
better matches that language-semantics rule, however, it's a terrible rule. The better way to deal with it is to (1) not allow multiple declarations and (2) distinguish the type from the identifier (e.g.int* i
orint& i
). Anyone with the least bit of knowledge in C/C++ knows about this rule, and so, we don't need to remind people of it, we just need to avoid it.