Search code examples
c++constantsauto

Difference between const auto & and auto & if object of reference is const


// case 1
const int i = 42;
const auto &k = i;

// case 2
const int i = 42;
auto &k = i;

Do we need the const keyword before auto in this scenario? After all, a reference (k) to an auto-deduced type will include the top level const of the object (const int i). So I believe k will be a reference to an integer that is constant (const int &k) in both cases.

If that is true, does that mean that const auto &k = i; in case 1 is replaced by the compiler as just const int &k = i; (auto being replaced with int)? Whereas in case 2, auto is replaced with const int?


Solution

  • auto keyword automatically decides the type of the variable at compile time.

    In your first case, auto is reduced to int where it's reduced to const int in the second case. So, both of your cases are reduced to the same code as:

    const int &k = i;
    

    However, it's better to have the const explicitly for better readability and to make sure your variable TRULY is const.