Search code examples
c++c++11constantsauto

Compound types, const and auto in C++


I'm trying to understand this piece of code. I'm stuck at figuring out why d and e are int* and const int*. I could use some help.

const int ci = i, &cr = ci;
auto b = ci; // b is an int (top-level const in ci is dropped)
auto c = cr; // c is an int (cr is an alias for ci whose const is top-level)
auto d = &i; // d is an int*(& of an int object is int*)
auto e = &ci; // e is const int*(& of a const object is low-level const)

Solution

  • &i means "take the address of i". Since i is a int, the type of &i is int*. The type of d is deduced as int* due to automatic type deduction rules.

    The same reasoning can be applied to ci. The only difference is the const qualifier.