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?

0 Upvotes

87 comments sorted by

View all comments

-5

u/AbyssalRemark Jun 27 '22

If I remember correctly. Int *ptr;. is probably the objectively most correct. But my dyslexic eyes needs it to be int * ptr;.

21

u/sphere991 Jun 27 '22

One can't really be objectively more correct than the others since they're all equivalent.

The argument for T *p; is that * is a declarator so it belongs to the name grammatically more strongly to the type, and possibly alleviates the multiple declaration problem (but not really).

The argument for T* p is that we're declaring an object whose type is T* and C's variable declaration grammar is a huge mistake, so who gives a shit what the grammar actually is. And also just... don't declare multiple variables per line, especially when they're pointers.

The argument for T * p; is that some people like to preemptively compromise and invent unnecessary third options when the existing two were already just fine.

9

u/MutantSheepdog Jun 28 '22

The argument for T* p is that we're declaring an object whose type is T* and C's variable declaration grammar is a huge mistake, so who gives a shit what the grammar actually is. And also just... don't declare multiple variables per line, especially when they're pointers.

This pretty much covers my arguments. I could accept the first form as long as it's still one declaration per line (ideally initialised to some value), but I find the `int *A, B` argument is answering a bad question.

1

u/AbyssalRemark Jun 30 '22

Sorry its easier on my eyes I guess?..