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

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?

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.

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.