Difference between char* var; and char *var;?

Joe DF picture Joe DF · Mar 4, 2013 · Viewed 12k times · Source

Just wondering if there's any difference between:

char* var;
char *var;

or is it just a matter of preference (spacing)?

Answer

cdhowie picture cdhowie · Mar 4, 2013

There is no difference in this case. However, you should prefer char *var;.

This is because the * is associated more closely with the variable name and is not part of the base type. For example, if you do this:

char* a, b;

What you have is a, a pointer-to-char, and b, a char. This is confusing! Since the * character is closer to the char keyword, we expect that the types of both variables will be pointer-to-char, but the * is actually associated only with a. (This is similar to char a[10], b; as pointed out by teppic in the comments; the [10] specifier is likewise only associated with a, and so only a will be an array.)

The correct declaration would be:

char *a, *b;

Putting the * specifier closer to the variable means that it's easy to see what's going on when you intend for one variable to be a pointer and the other not:

char *a, b;

In this case it's obvious that b was not intended to be a pointer. In the original example (char* a, b;), we don't know whether or not the programmer intended for b to be a pointer. To borrow from Douglas Crockford, all we know is that the programmer is incompetent.

Some people like to put a space before and after the *:

char * a, * b;

This falls prey to the same problem illustrated above: if b is not a pointer then the declaration (char * a, b;) may also lead to uncertainty about the programmer's intent. Therefore I suggest not placing a space between the * and the variable name1.

Any way you look at it, char* var; should be treated as bad style. It's grammatically correct according to the language specification, but leads to unreadable code because it appears to indicate that the * specifier is part of the type shared by all variables in the same declaration, when it is not. (It's akin to writing a complex function all on the same line -- it works, but it's a bad idea. There are cases where readability and maintainability supersede personal stylistic preferences, and this is one of them.)


1Personally, I prefer to put a space after the * only when dealing with function return values:

char * foo();

This is unambiguous: it's a function that returns a pointer-to-char.

char *foo();

Did the programmer mean a function that returns a pointer-to-char, or did he mean to create a pointer to a function that returns char? The language will resolve this as identical to the other prototype, but our goal is readability, and that means conveying exactly what we mean to humans, not just the compiler.