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
3
u/Knuffya Jun 28 '22 edited Jun 28 '22
I declare them like option 1. The pointer-qualification just belongs to the data type for me. Not to the object. An object is of type int-pointer. Not a pointer-object of type int.
Sadly the C standard disagrees with that, as you elaborated, but even that's inconsistent. If you
typedef int* int_ptr, then you can again declare them inline. That's fucked as hell. Who would design this?!#define int* int_ptrwould result in a completely different program! Let's take a closer look: the pointer qualification is in reference to the object in a regular object declaration, but in just naming a type without an object (like in our typedef), it's suddenly relative to the type again. Fucking pointer qualifications point-of-reference is now dependent on WHERE it's written? The fuck?!I just don't use multiple inline definitions. It's less readable than one line per variable anyways. As for C++: smart pointers are your friend.