int foo = 11;
int *p = &foo;
auto pp = p;
auto *ppp = p;
cout << pp << endl;
cout << ppp << endl;
This program will produce the same output for pp
and ppp
, but why? auto
deduces the variable should be int
, so I think the declaration of ppp
is right. But pp
and ppp
have the same value...
Output:
0x61fefc
0x61fefc
In the particular example you show, there is no difference. But imagine you would later on add two const
qualifier like the following:
const auto pp = p;
const auto *ppp = p;
Is it still the same? Turns out that this is identical to
int * const pp = p; // pointer is readonly
const int *ppp = p; // pointer is readonly
because in auto pp = p
, auto
matches int*
as a whole, and const
modifies what's on its left (or what's on its right, if there is nothing on its left). Contrary, in auto *ppp = p
, auto
matches int
, and this is what const
applies to.
Because of this notable difference and because we should use const
variables whenever possible, I'd advise you to always use auto*
when using type deduction for pointer variables. There is no way to const
-qualify the pointer itself instead of the pointee, and if you want to const
-qualify both, this is possible by
const auto * const pppp = p;
which doesn't work without the *
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With