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?
Jun 30 '22
1049
int* ptr;
66
int * ptr;
558
int *ptr;
36
others
0
Upvotes
6
u/CocktailPerson Jun 28 '22
int* ptr;Because I like consistency, and if I need to make the pointer itself const,int *const ptr = &x;is fugly. If you're using plain C, thenint *ptr;is fine, K&R used it and they wrote Unix.Arguing that one style makes multiple variable definitions per line look better is like arguing that a little sugar makes lead paint taste better. Haven't we all agreed it isn't good for you anyway?
But seriously, who cares? Write whatever you want and run clang-tidy before checking in.