开发者

Difference between int* p and int *p declaration [duplicate]

This question already has answers here: 开发者_运维技巧 Placement of the asterisk in pointer declarations (14 answers) Closed 2 years ago.

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


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.


  • 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.


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜