The danger with the syntax is in the following:
|
int* x, y; // Not what it looks like
| |
Many C++ programmers (and many unsuspecting C programmers) have thought that
y
was also a pointer, but it is not. It is equivalent to:
1 2
|
int * x; // pointer to int
int y; // int
| |
That’s right.
y
is just an int.
There are two conventions to combat that error. The first is newer, actually, but still older than C++ and alluded to by
mbozzi, which says
keep them dang asterisks with them variables:
|
int *x, *y; // both are pointers. yay!
| |
The other is also older than C++, and these days more common (I think), which says
one variable per type per line:
1 2
|
int * x; // pointer
int * y; // pointer
| |
This smells much cleaner and is definitely easier to read. Spacing around the asterisk no longer matters. The following are all equivalent while maintaining that same readability:
1 2 3 4
|
int*x;
int* x;
int *x;
int * x;
| |
I personally tend to the left for type names, and to the right for referencing and dereferencing.
1 2 3
|
int x = 7;
int* y = &x;
int& z = *y;
| |
But in the end it does not matter where the spaces go. Pick your preference for your own work, and use the project guidelines for other people’s work.
Hope this helps.