Skip to main content

Pointer Styling

The style guide states that we should declare pointer variables like this:

int* ptr;

However, you may run into code where pointers are declared like this:

int *ptr;

These are syntactically exactly the same! They mean the same thing. However...

This first version is semantically more clear... the understanding here is that ptr is the name of the variable and its datatype is an int* (integer pointer). It is like every other variable you have declared... there is a datatype, then a variable name.

int* ptr;

This other version is syntactically more correct.

int *ptr;

This is not noticeable until you try to declare two pointers on the same line. Suppose you wrote:

int* ptr1,ptr2;

If you did this, ptr1 would be an integer pointer. However ptr2 would actually be just an integer. This is because C syntax requires the * before each variable name to make it a pointer. Thus if we want both ptr1 and ptr2 to be int pointers, we would need to write:

int* ptr1, *ptr2;

This looks really awkward as the * seems to be positioned differently for these variables so to be consistent in styling we would write:

int *ptr1, *ptr2;

Having said this, one of the things we stated in our style guide is that we should declare one variable per line. Thus, we should not actually have a situation where there are two pointers declared on the same line. As a result, the clearer way to understand our code is to put the * with the data type and not the variable.