C - initialization of pointers, asterisk position [duplicate]

Solution 1:

It does not matter as far as you are declaring only one pointer. It is usually writen like in the second example (in the code I usually read/write) but for the compiler it's the same.

The trouble can come out if you are declaring more than one pointer. For example, this is not declaring two pointer, instead it declares one pointer and one var of type type.

type* var1, var2;

You need to do instead:

type* var1, *var2;

I prefer to use the * by the var always.

Solution 2:

Pointer is the type, and I think it makes most sense to group the type information:

int* foo;

This can lead to confusion if several variables are defined on the same line:

int* foo, bar;  // foo will be int*, bar will be int

The solution to this is, never declare several variables on the same line. Something that Code Complete advocates, anyway.

Solution 3:

Both work. I'd argue that #1 is clearer in general, but misleading in C and can lead to errors, e.g.:

type* var1, var2;

// This actually means:

type *var1;
type var2;

So I'd say that #2 is more idiomatic in C and therefore recommended, especially if you are not the only programmer working on the code (unless, of course, you all agree on a style).