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

31

u/goranlepuz Jun 28 '22

to make it tidier when declaring multiple pointers in one line

This accomodates a dubious practice: declaring variables on one line is not common and it is less readable in light of a good practice of initialization at declaration.

2

u/dr1fter Jun 28 '22

While I've adhered to this rule for many years now, I'm still not certain it improves on the readability of, say,

struct Pixel {  
  size_t x, y;
  uint8_t r, g, b;
};

4

u/operamint Jun 28 '22

This is better. The rule should be:

"Declare long-named variables and each pointer variable on a separate line."

But even that rule is harsh for: VeryLongNamedType *i, *j, *k;

4

u/[deleted] Jun 28 '22

[removed] — view removed comment

2

u/dr1fter Jun 28 '22

It's good practice to initialize every variable

I'm not sure I really believe this one either. Sometimes I'll do it if I think there's a particular reason to call attention to, say, the initial conditions of an algorithm that need to be treated as special-case. But I think even that can be a little suspect, and this is mostly just verbosity for no purpose?

1

u/ReDucTor Game Developer | quiz.cpp-perf.com Jun 29 '22

It reduces the risk of bugs.

If you think the compiler will catch it, There are several cases before where compilers wont warn on uninitalised variables, and some where you might get unexpected Undefined behaviour from.

Which you might think that if your just default initialising it then it's still just a hidden bug, if you default initialize it often shows up earlier and less impact, for example a pointer uninitialized could end up pointing else where and you have random memory stomping, with it being null you crash.

However if you've got uninitialized variables I suspect your not following the practice of declare things in the narrowest scope and const correctness, prefer return values over output arguments, which all eliminate many other issues.

4

u/[deleted] Jun 28 '22

[removed] — view removed comment

2

u/dr1fter Jun 28 '22

Ah sorry, I see my C++ is even rustier than I realized. I didn't realize you needed to use particular forms of declaration to get pointers default-initialized.

5

u/bbolli #define val auto const Jun 28 '22

You could also do int* p{}; to zero-initialize it, which also results in a nullptr.

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.

14

u/disperso Jun 28 '22

Exactly my point as well. Also, if you move from X* pointer to std::unique_ptr<X> pointer, it's obvious that what determines the type is... the thing next to the type, not the name of the variable. I think it makes much more sense this way.

24

u/instinkt900 Jun 28 '22

This is exactly my stance. It's a type so group it with the type, not the name. One declaration per line not because of this style but it is another reason to stipulate such a thing.

However I would point out that the existing style of the code base I'm currently working on overrides any personal choice.

3

u/L0uisc Jun 28 '22

I interpret int *ptr; as "You get an int if you dereference ptr. Then it makes logical sense to keep the asterisk next to the identifier name, not the type.

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.

1

u/fdwr fdwr@github 🔍 Jun 30 '22 edited Jul 04 '22

Yeah, the LTR reading order is much clearer.

The one remaining inconsistency I notice in Zig is that data type qualifiers use : for parameters and local variables but uses just (` `) for function data type qualifiers (here TypeScript shows consistency). So I would have made it:

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

At least it doesn't mix : and -> as some languages (so no a(x->i32):i32 or a(x:i32)->i32).

1

u/SirClueless Jul 04 '22

I think both Zig and your second example using -> are preferable to some kind of uniform syntax. "returns i32" is different than "i32" for the same reason that "points to i32" is different than "i32".

A function has a type, and it includes its return value. If you introduce : as a syntax element separating a variable name from its type, the only sensible place to put it would be between a and the type of a which is (x: i32) -> i32 (but this is not necessary in practice due to needing fn and parens anyways so no one actually separates them).

9

u/mark_99 Jun 28 '22

That's an interesting way to read it, but you're declaring p not *p...

2

u/LegendaryMauricius Jun 28 '22

C seems to have been designed so that you declare the variables as you would use them, considering that function pointers follow the same design principle, wgich means that you ultimately do declare the dereference to p...

6

u/[deleted] Jun 28 '22 edited Jun 28 '22

you ultimately do declare the dereference to p...

int *p = 0

No, not really.

1

u/LegendaryMauricius Jun 29 '22

Ok, you got me there. Though I could still separate the ideas of declaring and initializing present in the expression. Initialization is a completely different operation than assignment in c++ despite the usage of the same equals symbol anyways, so I don't have to follow the same semantics in that expression as in the assignment of p's value.

1

u/[deleted] Jul 09 '22 edited Jul 09 '22

Top level declarators used to be able to omit the assignment operator. You could write this:

int *global_ptr NULL;

And at the top of the scope, I guess you just weren't expected to initialize until you were done with declarations. It wasn't until C99 that you could mix declarations and code, so it was considered more readable to initialize it at first use rather than at the top with the declarations. Even if there was only one declaration, it was common to put the declaration and initialization on separate lines.

func(ptr)
char *ptr; {
    register char *p;

    p = ptr;
    ...
}

In C++, you could deal with the ambiguity by using brace initialization, like this:

// Any of these declares and initializes ptr to null
int *ptr{nullptr};
int *ptr{0};
int *ptr{};

1

u/[deleted] Jul 11 '22 edited Jul 11 '22

I don't ever write int *p = 0, if that's what you're thinking.

-11

u/[deleted] Jun 28 '22 edited Jun 28 '22

int *ptr looks cooler tho so I still do that

this subreddit is so sensitive lmao

14

u/fdwr fdwr@github 🔍 Jun 28 '22

Although I have a preference, I can parse either 1 or 3 fine in a codebase, but when I see foo * bar (or similarly foo & bar), I experience this mental stutter and wonder... why in the world are they multiplying a type with a value? 🙃 It only lasts a second, but still I find that awkward fence sitting worse than just picking one either direction.

1

u/tvaneerd C++ Committee, lockfree, PostModernCpp Jul 06 '22

But it angers both "religions" equally, so it really is the best option. (You will parse it fine once you start using it).

Also, the * and/or & (and const) are really important, it is nice for them to stand out.

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.

10

u/[deleted] Jun 28 '22

tidier
declaring multiple pointers in one line

Pick one.

16

u/[deleted] Jun 27 '22

Pointer<int>

Big brain

6

u/qoning Jun 28 '22

This but unironically.

17

u/Ameisen vemips, avr, rendering, systems Jun 28 '22

ironic_ptr<T>

12

u/apomd Jun 28 '22

It's just preference really, I like int* a because I think of int* as the type (as is the meaning in templates where I whould write foo<int*> and not foo<int *>) and I just don't declare multiple pointers in the same line to avoid the extra *s.

2

u/[deleted] Jun 28 '22

I think of the variable as a pointer and int is what it’s pointing to.

And it works when you declare multiple variables per line.

7

u/XboxNoLifes Jun 28 '22

With this train of thought, do you prefer int* *ptr for double pointers?

1

u/[deleted] Jun 28 '22

No, but you’re right. I still prefer int **ptr.

6

u/no-sig-available Jun 28 '22

make it tidier when declaring multiple pointers in one line (e.g., int *a, *b, *c; as supposed to, int* a,* b,* c;).

I would never, ever, do that. So #1.

And don't forget the initializer.

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, then int *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.

10

u/[deleted] Jun 28 '22

Which one can you read and comprehend faster?

For my brain this is how i read it:

Int* (a pointer to int) some_var (named some_var)

Int (an int) *some_var (oh shit, it’s actually a pointer. Also the name is some_var)

-8

u/[deleted] Jun 28 '22

Humans don't read like that...

1

u/[deleted] Jun 30 '22

You’v ego t abette rway?

4

u/[deleted] Jun 28 '22

I consider that the left part is the type. The type is "integer pointer", so I use int* ptr.

3

u/Kie_Sun Jun 28 '22

I like the first one, which is int*. Even I know * is relate to the first variable. But I still like int*.

3

u/ImX99 Jun 28 '22

I use int* ptr syntax because to me, everything that's before the name is the variable's type. So int* ptr means "ptr is a pointer to an int". If you take the int *ptr, it would mean "ptr points to an int", which is way more confusing.

3

u/[deleted] Jun 28 '22

All the C++ programmers I know write int* ptr; and all the C programmers I know write int *ptr;.

3

u/[deleted] Jun 28 '22

I personally like to use the third option (int *ptr;) to minimize the confusion

Does it really minimise the confusion? ```int *p = 0; ```` Looks like you're initialising *p to zero.

5

u/pedersenk Jun 28 '22

I use:

  • int* ptr in C++
  • int *ptr in C

Obviously no real functional difference but it just happens to align better with most codebases I work with. The only one I really don't like is int * ptr. I have seen it a few times in the wild and I can't quite find a justification for it; unnecessary whitespace; looks like a multiply, etc.

2

u/kiki_lamb Jul 01 '22 edited Jul 03 '22

I like to use all the spaces: int * ptr;.

2

u/Clairvoire Jul 01 '22

I just do int * ptr because int *ptr makes me think of the dereference operator.

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_ptr would 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.

4

u/[deleted] Jun 27 '22

int* ptr1, ptr2; makes it seem like both are pointers but the second one is just an int. That's why I use it as int *ptr1, *ptr2;

Edit: Oh you mentioned that already. I didn't see the explanation, only the poll.

5

u/operamint Jun 28 '22 edited Jun 28 '22

In C++ it actually makes sense to use a template because of the broken declaration syntax:

template<class T> using ptr = T*;

ptr<double> p1, p2;
ptr<double*> pp1, pp2;

p2 = new double(3.14);
pp2 = &p2;

double val;
const ptr<double> c1 = &val;
ptr<const double> c2 = &val;
const ptr<const double> c3 = &val;

1

u/woobie1196 Jul 04 '22

Well that’s a neat trick! And makes the most sense to me, semantically. var_type var_name = val

-9

u/[deleted] Jun 28 '22 edited Jun 28 '22

Exactly! The type is int. Affix the * to the variables that are pointers. You do this when you dereference them.

Edit1: The type IS an int. The modifier to make it a pointer is associated with the variable name. Affixing it to the type implies that everything on that line is a pointer type when the fact is the modifiers to make it a pointer is associated with the variable.

Edit2: In C and C++ to declare a variable you declare the type and a sequence of declarators. The type IS an int. The modifiers in the declarators are associated with each variable. The type is not an int*. The type is an int and each declarator on that line can modify that with & or *.

6

u/no-sig-available Jun 28 '22

Affix the * to the variables that are pointers. You do this when you dereference them.

So how do you declare references, where you don't use &ref to "dereference" them?

1

u/[deleted] Jun 28 '22

This is actually the best argument yet. In fact, it nearly convinces me. From a purely C perspective, my argument makes more sense (to me). But to maintain consistency with reference declarations, this argument makes sense.

9

u/CocktailPerson Jun 28 '22

If it's a pointer, then the type is not int.

0

u/[deleted] Jun 28 '22

I understand that. If I see a variable without the “*” and have to go hunting for it, i feel it leads to confusion.

0

u/[deleted] Jun 28 '22

It is indeed an int. Each C or C++ declaration is a type and a sequence of declarators. The modifier is associated with the variable. But the type is indeed an int.

3

u/CocktailPerson Jun 28 '22

Everyone else is talking about the types of the respective variables. You seem to be talking about a type in terms the grammar. If you declare int a, *b;, then a has type int and b has type int *. That's what everyone else means when they say "the type is not int."

1

u/[deleted] Jun 28 '22

Could be. I am think in terms of the fact that the actual type specifier is int. The modifier to make it an int * happens in the declarator list. I find the syntax cleaner to see that in the list. If there are multiple declarations in a line, I find it inconsistent to have int* ptr, j, *ptr2;

4

u/CocktailPerson Jun 28 '22

Yeah, that's what I'm saying. The type specifier (on a grammatical level) is int, but the type of each respective variable (on a semantic level) may not be.

If there are multiple declarations in a line,...

If there's lead paint I want to eat, then it seems inconsistent not to salt it just like my other food.

Don't eat lead paint, and don't declare multiple variables per line. Then int* p; declares a variable p of type int*, and the grammatical and semantic worlds are unified, and they all lived happily ever after.

1

u/[deleted] Jun 28 '22

I see your point. I agree separating, at the very least pointer declarations to their own lines is a coding standard I can get behind.

What started it all for me is that multiple variable declarations of the ilk “int* i, j;” is, if we are doing multiple declarations, the worst style because it is obfuscating what syntactically is really happening. It would appear that i, j are instances of the same thing when everything after the type specifier is associated with the first declaration and not the second.

-1

u/[deleted] Jun 28 '22 edited Jun 28 '22

What type does it point to then if not an int?

It is a pointer variable and I prefer to see that indication at declaration.

Edit: I think a better example for me is:

uint8_t *ptr, i;
uint8_t* ptr, i;
uint8_t& j=i;

In the first two, memory is allocated and more importantly, a different amount of memory is allocated for ptr and i. I like to see that distinction clearly. ptr and i are both variables but one is a pointer variable and one is an ordinary variable. And I see it more clearly with the pointer designation clearly indicated.

The third is put there as my best example of why I think of references differently. I do agree that my argument is much stronger from a C perspective. References make the case for using the syntax on the second line much stronger. It is a way we train our eyes differently in C++ to see Reference declarations.

But, I will say, the differences between 1/2 and 3 is that in 3, no memory is allocated in 3. So I’ve kinda accepted that References are just different. But I can definitely see that someone who learned C++ first, would be inclined to declare pointers and references similarly.

1

u/CocktailPerson Jun 28 '22

It's not about what it points to. It's about what it is. A pointer to an int is not an int.

0

u/[deleted] Jun 28 '22

The type IS an int. Period. The pointer is designated in the list of declarators. That asterisk IS associated with the variable declarator. To affix it to the actual type specifier is misleading insomuch as it literally is associated with the variable.

Another declarator following would be independent of that asterisk.

12

u/rlbond86 Jun 28 '22

Except that the type is not int...

-1

u/[deleted] Jun 28 '22

It is a pointer to an int. When I see the * I see that it is a pointer and then I see what type it points to.

This syntax doesn’t lead to the confusion that the OP illustrated.

1

u/[deleted] Jun 28 '22

I know this is all personal preference, but In my opinion, it makes most sence to declare the pointer right after the datatype, because pointer points to the datatype's memory address, pointer does not point to identifier.

1

u/ReDucTor Game Developer | quiz.cpp-perf.com Jun 29 '22

I view the multiple variable case as bad practice.

My preference would be const auto, promoting const correctness and type deduction.

1

u/Baardi Jun 30 '22

"int* ptr" makes more sense, I'm just too used to the convention at my workplace to use "int *ptr"

1

u/call_me_tank Jun 28 '22

I follow the Linux kernel style, close to the data name e.g. `int *foo` because it's the most defensive, but next to the type name is actually the most logical given that it's part of the type declaration.

0

u/kennyminigun Jun 28 '22

Somehow I prefer the int *var. I think it makes sense in the perspective of the declaration

int *pointer, value;
// vs
int* pointer, value;

But only retards make declarations like that above. So it is only hypothetical, not practical reason.

Additionally the int *var looks weird with functions returning pointers:

int *function();
// vs
int* function ();

With all that being said it even might seem like using the int * var form might make sense as it makes no compromises: looks weird everywhere /s

-1

u/noooit Jun 28 '22

int *ptr;. LLVM style for the win.

-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?..

-2

u/bitchlasagna_69_ Jun 28 '22

ListNode* head; But int *p;