Rohan
Rohan

Reputation: 29

What the difference between int *p and int* p

I have seen many codes where they use int* to declare variables. I know int*p declares a variable of type integer which is a pointer. But what does int* p do? for example :

int* x,y,z;

Does this mean all the three variables are pointers? Can we use int *x,*y,*z instead of this?

Upvotes: 0

Views: 2457

Answers (2)

Mike Seymour
Mike Seymour

Reputation: 254451

What the difference between int *p and int* p?

Except where it's needed to separate tokens (which it isn't here), whitespace never affects the meaning of C++ code. Both have identical meanings (as to int * p and int*p); the spacing is purely a matter of taste.

Does this mean all the three variables are pointers?

No, only the first is a pointer. In this case, the spacing is slightly misleading, so some would prefer to make the association clearer:

int *x, y, z;

or, better still, don't try to declare variables of multiple types in a single declaration:

int * x;
int y,z;

If you want them all to be pointers, then you have to specify it for each:

int *x, *y, *z;  // adjust spacing to taste

Upvotes: 5

barak manos
barak manos

Reputation: 30136

There are two ways to "look at" variable p:

  • You can consider p as a variable of type int*.

  • You can consider *p as a variable of type int.

Hence, some people would declare int* p, whereas others would declare int *p.

But the fact of the matter is that these two declarations are identical (the spaces are meaningless).

You can use either p as a pointer to an integer value, or *p as the actual pointed integer value.

Assuming that p is pointing to a valid memory address, and depending on access permissions:

  • You can get (read) the pointed data, for example, int c = *p.

  • You can set (write) the pointed data, for example, *p = 5.


When declaring several variables on the same line, the compiler assumes the type without the asterisk.

Therefore, with int *x,y,z, only x is regarded as an int pointer.

If you wish to have y and z regarded as int pointers, then you need to use int *x,*y,*z.

So using a space between the type and the asterisk is possibly a better coding-convention.

Personally, I always declare pointer variables in separate lines (one line per variable).

Upvotes: 1

Related Questions