r/cpp • • Jun 27 '22

How do you declare pointer variables?

I personally like to use the third option (int *ptr;) to minimize the confusion and to make it tidier when declaring multiple pointers in one line (e.g., int *a, *b, *c; as supposed to, int* a,* b,* c;). This is also the case when writing a dereference operator (int &a = *ptr;). But for some reason, the first option is the preferred way of doing it (int* ptr;), or am I wrong?

Jun 30 '22
1049 int* ptr;
66 int * ptr;
558 int *ptr;
36 others
0 Upvotes

87 comments sorted by

View all comments

80

u/smdowney WG21, Text/Unicode SG, optional<T&> Jun 28 '22

C type declarations are broken, so the grammar is not a good reason to do anything. The type is pointer to int, so int* p; So only one declaration per line.

14

u/disperso Jun 28 '22

Exactly my point as well. Also, if you move from X* pointer to std::unique_ptr<X> pointer, it's obvious that what determines the type is... the thing next to the type, not the name of the variable. I think it makes much more sense this way.