Difference between int* p and int *p declaration

27,713

Solution 1

There is no difference.

It's a matter of notation, not semantics. The second is less misleading, because

int *a, b;

is clearly declaring an int* and an int, whereas

int* a, b;

looks as if it's declaring two pointers, when it's really doing the same thing as above.

Solution 2

  • int* p

    • widely used by C++ programmers
    • int* p, q wrongly implies that both p and q are pointers (leading to a preference for declaring this on two lines, which also improves readability when there are assignments, and makes it easier to quickly cut/paste or comment specific lines/variables)
    • int* p visually separates the type from the identifier
    • *p then unambiguously indicates a dereference (assuming you put spaces around your binary operator* ala 2 * 3)
    • in C++ ...&x is clearly taking an address while ...& x must be declaring a reference variable, and ... & ... is the bitwise-AND operator
  • int *p

    • widely used by C programmers
    • int *p, q clearly reflects p being a pointer and q not being.
    • int *p visually confuses the type with the identifier
    • visually indistinguishable from a pointer dereference (for better or worse)

Similarly for types appearing in function declarations...

int* f(), g();  // declares int g();
int *h(), (*i)();  // i is pointer to function returning int
int *const*m(), n(); // m returns pointer to (const-pointer to int)
                     // n returns int

...but at least function arguments can't get so hairy - the type specification starts afresh after each comma separators.

Summarily, int *p is better if your coding style / code-base utilises multiple declarations on a single line of source code, otherwise int* p offers a clearer separation of type and the following identifier.

For all that, people's preferences are largely based on what they're used to.

Solution 3

They are the same. The first one considers p as a int * type, and the second one considers *p as an int.

The second one tells you how C declarations simply work: declare as how would be used.

The Internet is flooded with complex approaches to parse declarations like "clockwise/spiral rule" and "the right rule". People makes the simple one complex: why do we need to read these types out loud? We only need to know how to use it!

By the way, the first one sometimes make you mad. Consider this:

int* p, q;

You would like p and q both becomes int *, but unfortunately not.

If you write int *p, *q, things will be simpler.

Anyway you can try this if you insists on approach one.

typedef int* intp;
intp p, q;
Share:
27,713

Related videos on Youtube

karthik
Author by

karthik

.NET Developer having experience in MVC, Web Development, WCF Services.

Updated on July 09, 2022

Comments

  • karthik
    karthik almost 2 years

    What is the difference between an int* p and an int *p declaration?

Related