Position of the star when declaring C pointers

There is a great debate in C-style languages about the position of the asterisk and the space when declaring pointers:

MyType *x; // Original C style
MyType* x; // The other style

I was reminded of this when attending an Objective-C training course recently. Apple's tools create declarations of the first form, the trainer preferred the second form. I remember having an opinion on this debate back when I first came across the second form, good to see that debate is still alive and well.

The logic for the second type is that x is a "pointer to MyType" and therefore one should separate the type (MyType*) from the name of the variable. That would make sense however the syntax of C doesn't work that way. The line

MyType* x,y;

is confusing, it appears to imply that both x and y are pointers to MyType. I have read many times that this is dangerous, and the solution is never to declare more than one variable on a line.

However in fact it's not dangerous at all, and one needn't remember an arbitrary rule to remove this danger. The star is in the wrong place, and that's where the confusion comes from. If one writes the statement differently:

MyType *x, y;

Then it becomes clear that only x is the pointer and y is not a pointer.

Therefore, I must side with Apple's tools as opposed to our trainer. One has to use the syntax as it was intended, and it was intended that the type is adopted by all variables in a declaration, the level of indirection (pointers) however is not. As that's the case, and cannot/will not be changed, the level of indirection (the number of stars) must be next to the variable name, and not the type.

In my opinion, to write the star next to the type should be a compile error.

P.S. I recently created a nerdy privacy-respecting tool called When Will I Run Out Of Money? It's available for free if you want to check it out.

This article is © Adrian Smith.
It was originally published on 7 Jan 2011
More on: Coding