when I declare C++ variables, I do it like this:
int a,b,c,d;
or
string strA,strB,strC,strD;
I.e., first
The reason is: in reality &
and *
in C and C++ applies to variable and no to type.
So the problem is that if you want to declare 4 pointer to integers you should write
int *a, *b, *c, *d;
Writing int* a, b;
means
int *a;
int b;
For this reason a lot of people prefer to write int *a;
than int* a;
, just code style.
Of course int*
is a type, but the C syntax states clearly that in a variable declaration *
and &
will apply to variable.
This happens for the same reason that arrays in C are declared in this way:
int a[10], b;
std::cout << typeid(a).name() << std::endl; // it will print int[10]
std::cout << typeid(b).name() << std::endl; // it will print int
In other languages like C# instead the syntax int[] array;
is used.
Another thing is the pointer to function syntax:
// Now we declare a variable that is a pointer to function
int (*pt2Function)(char, char) = NULL;
We are applying the *
to the variable name.
It seems to me that the use of *
and &
applied to the variable, also if 90% of us would prefer differently, is more consistent with the rest of the language.
In the same way, going back to arrays:
// Now we declare a variable that is a pointer to an array of 10 integers.
int (*arrayptr)[10];