Ali-Ibrahim
Ali-Ibrahim

Reputation: 999

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

Upvotes: 1

Views: 107

Answers (1)

Aleksandr Medvedev
Aleksandr Medvedev

Reputation: 8978

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.

Upvotes: 6

Related Questions