Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between const auto * and const auto?

I have this code:

const int a = 10;
const auto *b = &a; //0x9ffe34
const auto c = &a; //0x9ffe34

int z = 20;
b = &z; //0x9ffe38
//c = &z; //[Error] assignment of read-only variable 'c'

Why can you assign a new address to b and not to c?

like image 214
Dirty Oleg Avatar asked Apr 12 '16 03:04

Dirty Oleg


1 Answers

b will be deduced as const int*, which means a non-const pointer pointing to const int, so it's fine to change the value of b itself.

c will be deduced as const int * const, which means a const pointer pointing to const int, so you couldn't change the value of c itself.

Explanation

For this case auto specifier will use the rules for template argument deduction.

Once the type of the initializer has been determined, the compiler determines the type that will replace the keyword auto using the rules for template argument deduction from a function call.

For const auto *b = &a;, and &a is const int*, then auto will be replaced as int, then b will be a const int*.

For const auto c = &a;, auto will be replaced as const int*, then c will be a const int* const. Note the const is the qualifier on c itself in const auto c.

like image 91
songyuanyao Avatar answered Oct 02 '22 15:10

songyuanyao