Is there a convention for pointer declarations in C?

There is absolutely no difference in functionality between

int* ptr;

and

int *ptr;

Which you use is up to you, there are multiple conflicting coding styles to choose from.


Something nobody else has mentioned is that

int *ptr;

corresponds more closely to the language grammar.

  • int *ptr; is a declaration, which consists of:
    • a declaration-specifier int, followed by
    • a declarator, *ptr.

(That actually skips a number of steps, but it gets the basic idea across.)

Since declaration follows use, what this means is that *ptr is of type int. It follows from this that ptr is of type int*.

One could argue that this makes it better than

int* ptr;

for the same reason that

x = y+z;

is better than

x=y + z;

Of course you can write

int* ptr;

and read it as "ptr is of type int*". And plenty of programmers do exactly that, and get along just fine (it tends to be the preferred style in C++). The compiler doesn't care which way you do it, and anyone reading your code shouldn't have trouble understanding it either way.

But whichever spacing you choose, you need to understand what int *ptr; really means, so that when you see

int *ptr, i;

in someone else's code (as you inevitably will), you'll immediately understand that ptr is a pointer and i is an int.

And if you're working with other programmers on a project, you should follow whatever existing convention is in the coding standards, or if there isn't one, the way the code is already written. I personally prefer int *ptr; to int* ptr;, but using a mixture of both styles is far worse than using either one consistently.


It matters only when you plan to declare multiple variables of the same type on the same line. For example, if you want multiple int pointers, you need to do this:

int *a, *b, *c;

Stylistically though, this is confusing when you're only declaring a single variable. Many people like to see the type followed by the variable name, and the type is supposed to be pointer to int, not int, so they prefer:

int* a;
int* b;
int* c;

It's ultimately up to you whether you prefer one form over the other. In 20 years of programming C professionally, I've seen about 50% of people choose one over the other.


They both mean the same as others have said. There is a trap waiting for you though. Consider this code:

int* a, b;

You might think that this declared to pointers to int. No so but otherwise. In fact a is int* but b is int. This is one of the reasons for many C programmers preferring to put the * next to the variable rather than the type. When written like this:

int *a, b;

you are less likely to be misled as to what a and b are.

Having said all that, many coding standards insist that you declare no more than one variable per line, i,e.

int* a;
int b;

If you follow the one variable per line rule then there is definitely no scope for confusion.