What's the difference between `auto pp` and `auto *ppp`?

  • A+
int foo = 11; int *p = &foo;  auto pp = p; auto *ppp = p;  cout << pp << endl; cout << ppp << endl; 

This program will produces the same output of pp and ppp,so why? auto deduce the variable should be int, so I think 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 a const qualifier to both variables:

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; // pointee 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 *.

