Difference between int* p and int *p declaration [duplicate]
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 bothp
andq
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 binaryoperator*
ala2 * 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 reflectsp
being a pointer andq
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;
精彩评论