Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Did I just change const value in C++ using refrence?

Code:

#include <iostream>

int main() {
  int a = 137;
  const int &b = a;
  std::cout << a << " " << b << std::endl;  // prints 137 137
  a++;
  std::cout << a << " " << b << std::endl;  // prints 138 138
}

The value of variable b becomes 138 after a++ statement, although it’s declared as const Shouldn’t this be not allowed? how to make sure this won’t happen? or at least get a warning for doing that.

I am using GNU GCC Compiler

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Shouldn’t this be not allowed?

It’s fine. Your code only prevents the b reference from changing the value, but the original variable a doesn’t have such a restriction, so it can be freely changed.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading