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?

Jun 30 '22
1049 int* ptr;
66 int * ptr;
558 int *ptr;
36 others
0 Upvotes

87 comments sorted by

View all comments

80

u/smdowney WG21, Text/Unicode SG, optional<T&> Jun 28 '22

C type declarations are broken, so the grammar is not a good reason to do anything. The type is pointer to int, so int* p; So only one declaration per line.

1

u/nikr0mancer Jun 28 '22

You can also say that *p type is int.

7

u/sphere991 Jun 28 '22

Okay now explain int& r; The type of &r is... not exactly int

2

u/LegendaryMauricius Jun 28 '22

Now that's a c++ thing. The semantics got lost in the newer language.

7

u/sphere991 Jun 28 '22

Yes, I'm aware. But the semantics were always bad.

Consider how easy it is to write and read a function that takes an int and returns an int.

Consider how excruciatingly difficult it is to write or read a function that takes a pointer to an array of N ints and returns a pointer to an array of N ints.

That's still C, and yet it's all-but-impossible without typedefs?

Compare that to a the much better semantics that Zig has, where all the "declarators" go on the same side and just stack linearly, making both functions equivalently easy:

fn a(x: i32) i32 { ... }
fn b(y: *[N]i32) *[N]i32 { ... }

1

u/LegendaryMauricius Jun 29 '22

It's definitely bad semantics, but it's imo easier to follow when you know the idea behind it, which I've never seen being thought in classes.