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