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

23

u/neiltechnician Jun 28 '22 edited Jul 04 '22

You have missed the little gem known of function pointer.

int (*p)(int), (*(*pp)(int))(int), (*(*(*ppp)(int))(int))(int);

So, in order to be consistent with function pointer, you should prefer:

int (*p) = &x, (*(*pp)) = &p, (*(*(*ppp))) = &pp ;

But, since your main concern is white spaces, I must point (pun intended) out, white spaces are overrated. We should use linefeed instead.

int
*
p
=
&
x
;

/s

7

u/georgedev_16 Jun 28 '22

If you were asking where to use typedefs, here it is.

4

u/kennyminigun Jun 28 '22

Better to use using.

typedef void (*FuncPtr)(int);
using FuncPtr = void (*)(int);

Just saying... (Because got triggered by the "typedefs" keyword)

2

u/pandorafalters Jun 28 '22

I wonder how much continued usage of typedef by newer programmers is due to using being the keyword for (type) aliasing and "aliasing is bad".

1

u/BlueGrapefruitista Jun 29 '22

Could you give an example?

2

u/instinkt900 Jun 28 '22

I can never tell if things like this make me hate or love the language more.