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.

-9

u/[deleted] Jun 28 '22 edited Jun 28 '22

Exactly! The type is int. Affix the * to the variables that are pointers. You do this when you dereference them.

Edit1: The type IS an int. The modifier to make it a pointer is associated with the variable name. Affixing it to the type implies that everything on that line is a pointer type when the fact is the modifiers to make it a pointer is associated with the variable.

Edit2: In C and C++ to declare a variable you declare the type and a sequence of declarators. The type IS an int. The modifiers in the declarators are associated with each variable. The type is not an int*. The type is an int and each declarator on that line can modify that with & or *.

6

u/no-sig-available Jun 28 '22

Affix the * to the variables that are pointers. You do this when you dereference them.

So how do you declare references, where you don't use &ref to "dereference" them?

1

u/[deleted] Jun 28 '22

This is actually the best argument yet. In fact, it nearly convinces me. From a purely C perspective, my argument makes more sense (to me). But to maintain consistency with reference declarations, this argument makes sense.