Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the position of the * or & matters? [duplicate]

Tags:

c++

pointers

Possible Duplicates:
In C, why is the asterisk before the variable name, rather than after the type?
What's your preferred pointer declaration style, and why?

In C++, i see pointers put in different ways. for example,

char* ptr
char * ptr
char *ptr

Are the 3 examples above identical? (same goes with the &)

like image 975
andrew Avatar asked Oct 31 '25 01:10

andrew


1 Answers

Doesn't matter. (Eg. they are the same.) You could even write char*ptr; without any whitespace.
Beware though with multiple declarations on one line: char* ptr, noptr;. Here, the third syntax comes in clearer: char *ptr, noptr;.
My rule to avoid that confusion: Only one variable per line. Another way to do it right without the possibility to miss a *: typedef the pointer, eg:

typedef char* CharPtr;
CharPtr ptr1, ptr2; // now both are pointer

Though then you need to be aware of other things, like constness, so I stick to my rule mentioned above:

typedef char* CharPtr;
const CharPtr p1; // const char* ?? or char* const ??
CharPtr const p2; // char* const ?? or const char* ??
// Eg.: Can't the pointer or the pointee be changed?

(And all of the above also applies to references &.)

like image 116
Xeo Avatar answered Nov 02 '25 16:11

Xeo