A const & refers to a nonvolatile variable. The variable changes. Does the change invalidate the const &?

  • A+

In C++, can the value of a const & change?

Well, of course it cannot change, can it? That's what const means. But what about this?

#include <iostream>  int main() {     int           a = 0;     const int&    r = a;     const int old_r = r;     ++a;     const int new_r = r;     std::cout       <<      "old_r == " << old_r       << " but new_r == " << new_r << std::endl;     return 0; } 

On my machine, this outputs, old_r == 0 but new_r == 1.

That gets to my real question. In the above code, look at the line

    const int new_r = r; 

Insofar as

  • the address &new_r is extracted neither on this line nor elsewhere in the code and
  • the code has nothing volatile,

does anything prevent an optimizing compiler from merging old_r and new_r into a single constant object, treating the line as though it read as follows?

    const int& new_r = old_r; 

I ask because, as far as I know, if the compiler did so optimize, that might alter the behavior. The program might output, old_r == 0 but new_r == 0.


The most nearly related existing question I find is this one:

The following are also related but, unlike the present question, involve casts:

See also N4659 (draft C++17 standard), sect., "The cv-qualifiers."


In C++, can the value of a const & change?

Yes, this is perfectly legal. Taking a const& to some variable doesn't stop that variable from being able to be modified, it just means you can't modify the variable through the reference. That means

int a = 42; int const& b = a; ++a; std::cout << a << " " << b; 

will print

43 43 

Had I tried to do


though that would be a compiler error as b's access to the value is const and ++ is a non const operation.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: