What makes more sense - char* string or char *string? [duplicate]

Solution 1:

In the following declaration:

char* string1, string2;

string1 is a character pointer, but string2 is a single character only. For this reason, the declaration is usually formatted like:

char *string1, string2;

which makes it slightly clearer that the * applies to string1 but not string2. Good practice is to avoid declaring multiple variables in one declaration, especially if some of them are pointers.

Solution 2:

Bjarne Stroustrup has something to say about this:

The critical confusion comes (only) when people try to declare several pointers with a single declaration:

int* p, p1; // probable error: p1 is not an int*

Solution 3:

Technically, it makes sense to write

char *f

Because *f is the declarator in that, while the char is the declaration specifier which specifies a basic type of all the declarators. The declarators contain operators like (), [] and & which can be thought of modifying the base type, and the actual identifier.

I use the above form of putting * to the identifier because it emphasizes that *f actually is the declarator, while char is the basic type.

To a degree, one can think of the modifiers in a declarator to make the type in the declaration specifier when the operators are applied to the identifier. But it does not always work:

int a, *b, &c = a, d(), e[1], C::*f;

Note how all of a, *b, d() and e[1] statically resolve to an int - apart from &c and C::* which declare a reference (thus it needs to be initialized) and a pointer to a class member respectively.

Solution 4:

What no one mentioned yet is that the following

char *string

can also be read as declaring the type of the expression *string (read: the indirection operator applied to the pointer string) as char. From this point of view, the notation is perfectly reasonable.

That being said, I use

char * string

myself ;)