views:

1215

answers:

6

In my experience, everyone names variables like this:

int *myVariable;

Rather than like this:

int* myVariable;

Both are valid. It seems to me that the asterisk is a part of the type, not a part of the variable name. Can anyone explain this logic?

+14  A: 

If you look at it another way, *myVariable is of type int, which makes some sense.

biozinc
This is my favorite explanation, and works well because it explains C's declaration quirks in general--even the disgusting and gnarly function pointer syntax.
Benjamin Pollack
It's sort of neat, since you can imagine there isn't any actual pointer types. There are only variables that, when appropriately referenced or dereferenced, gives you one of the primitive types.
biozinc
That's actually an excellent point, thanks!
ReaperUnreal
A: 

Because it makes more sense when you have declarations like:

int *a, *b;
Greg Rogers
+30  A: 

They are EXACTLY equivalent. However, in

int *myVariable, myVariable2;

It seems obvious that myVariable has type int*, while myVariable2 has type int. In

int* myVariable, myVariable2;

it seems obvious that both are of type int*, but myVariable2 does NOT have this type.

Therefore, the first programming style is more intuitive.

luiscubal
perhaps but I wouldn't mix and match types in one declaration.
BobbyShaftoe
A: 

A lot of it is personal preference and style. I've seen both but use the former (int *myVariable).

However, there are some technical reasons to put the asterisk with the name. If your coding conventions/style allows more than one declaration per line you may write:

int valA, valB;
int *pValA, *pValB;

pValA and pValB are definitely pointers to int types.

int valA, valB;
int* pValA, pValB;

pValA is a pointer to an int type; what's pValB?

Your answer may depend on your compiler but in most modern compilers pValB is a straight-up int . Keeping the asterisk with the name helps the person who comes after you or you in 6 months.

Better yet, only declare one variable per line.

dwj
+4  A: 

Because the * binds more closely to the variable than to the type:

int* varA, varB; // This is misleading

However, even the best single-line declarations seem counter-intuitive to me, because the * is part of the type. I like to do this instead:

int* varA;
int* varB;

As usual, less the compact your code, the more readable it is. ;)

ojrac
+3  A: 

That's just a matter of preference.

When you read the code, distinguishing between variables and pointers is easier in the second case, but it may lead to confusion when you are putting both variables and pointers of a common type in a single line (which itself is often discouraged by project guidelines, because decreases readability).

I prefer to declare pointers and references with their corresponding sign next to type name, e.g.

int* pMyPointer;
int& myReference;
macbirdie