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

4

u/[deleted] Jun 27 '22

int* ptr1, ptr2; makes it seem like both are pointers but the second one is just an int. That's why I use it as int *ptr1, *ptr2;

Edit: Oh you mentioned that already. I didn't see the explanation, only the poll.

5

u/operamint Jun 28 '22 edited Jun 28 '22

In C++ it actually makes sense to use a template because of the broken declaration syntax:

template<class T> using ptr = T*;

ptr<double> p1, p2;
ptr<double*> pp1, pp2;

p2 = new double(3.14);
pp2 = &p2;

double val;
const ptr<double> c1 = &val;
ptr<const double> c2 = &val;
const ptr<const double> c3 = &val;

1

u/woobie1196 Jul 04 '22

Well that’s a neat trick! And makes the most sense to me, semantically. var_type var_name = val