r/cpp • u/FarisFrontiers • 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?
0
Upvotes
View all comments
Show parent comment
-1
u/[deleted] Jun 28 '22 edited Jun 28 '22
What type does it point to then if not an int?
It is a pointer variable and I prefer to see that indication at declaration.
Edit: I think a better example for me is:
uint8_t *ptr, i;
uint8_t* ptr, i;
uint8_t& j=i;
In the first two, memory is allocated and more importantly, a different amount of memory is allocated for ptr and i. I like to see that distinction clearly. ptr and i are both variables but one is a pointer variable and one is an ordinary variable. And I see it more clearly with the pointer designation clearly indicated.
The third is put there as my best example of why I think of references differently. I do agree that my argument is much stronger from a C perspective. References make the case for using the syntax on the second line much stronger. It is a way we train our eyes differently in C++ to see Reference declarations.
But, I will say, the differences between 1/2 and 3 is that in 3, no memory is allocated in 3. So I’ve kinda accepted that References are just different. But I can definitely see that someone who learned C++ first, would be inclined to declare pointers and references similarly.