Possible Duplicate:
Declaring pointers; asterisk on the left or right of the space between the type and name?
Does it matter where I place the asterisk when declaring pointers in C++?
I searched, but my keywords don’t seem to fit. I’m pretty sure this question has already been asked., so point me in some direction if you know a link or something !
My question is, why do so many people use
TypeIdentifier *varname;
Instead of
TypeIdentifier* varname;
which is much more logical to me as the * modifies the type and not the variable name.
In both C and C++, the declaration syntax (mostly) follows usage.
The declaration
can be read as “
nis of typeint*“, or as “*nis of typeint“. And if you take a look at the language grammar, the latter corresponds more closely to the way it’s parsed.For a type consisting of just a name (like
int) and a*, it doesn’t make a whole lot of difference, but it matters for more complex declarations.The usual tendency is to use
int *n;in C andint* n;in C++. The latter is because that’s Stroustrup’s personal preference. His point, I think, is that the “nis of typeint*” reading is more natural, and the complexities can be avoided by not writing complex declarations. For example, whichever spacing you prefer, it’s better to writethan either
or