Home > Net >  Did I just change const value in C using refrence?
Did I just change const value in C using refrence?

Time:09-06

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

CodePudding user response:

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.

  •  Tags:  
  • c
  • Related