20
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
Boann
  • 48,794
  • 16
  • 117
  • 146
Bob liao
  • 569
  • 4
  • 15

2 Answers2

30

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

gsamaras
  • 71,951
  • 46
  • 188
  • 305
lubgr
  • 37,368
  • 3
  • 66
  • 117
  • Subtle, and important to know, and I don't recall reading this in any recent C++ book, e.g., Stroustrup's `Tour` 2nd ed. (I may have missed it.) – davidbak Nov 29 '18 at 15:10
  • Actually you didn't add const qualifier _to both variables_. You instead added it to the first variable and to the pointee of the second one. – Ruslan Nov 29 '18 at 15:13
  • 2
    @davidbak I agree, this is not super obvious. It bit me once, and as painful learning is quite effective, I remember since then :) – lubgr Nov 29 '18 at 15:14
  • 2
    Yepppp! _Painful learning is quite effective_ but unfortunately time consuming (and sometimes frustrating). Reading a nice explanation (making things obvious) is the 2nd best option (and much less time consuming). – Scheff's Cat Nov 30 '18 at 09:12
7

There is no difference in auto and auto * in this particular case. In case of auto pp = p; type will be deduced to int * while in case of auto *ppp = p; type will be deduced to int.

auto qualifier:

For variables, specifies that the type of the variable that is being declared will be automatically deduced from its initializer. [...]

Note that unlike auto the auto * will deduce only pointer types.

haccks
  • 104,019
  • 25
  • 176
  • 264