3

I could not understand why in below code snippet reference and its associated variable are giving different results.

const int x = 10;
const int &ptr = x; 
int& y = const_cast<int&>(ptr);
y = 19;
std::cout << "x = " << x << " ptr=" << ptr << " y=" << y << std::endl;

Output:

x=10 ptr=19 y=19

As per my understanding references are just alias for variable so why ptr is 19 and x is 10? Is this something to do with const or const_cast ?

LogicStuff
  • 19,397
  • 6
  • 54
  • 74
PapaDiHatti
  • 1,841
  • 19
  • 26

2 Answers2

8

From 5.2.11 Const cast [expr.const.cast]:

Note: Depending on the type of the object, a write operation through the pointer, lvalue or pointer to data member resulting from a const_cast that casts away a const-qualifier may produce undefined behavior (7.1.6.1). — end note ]

You're performing undefined behavior, so you're quite (un)lucky that your computer didn't implode. :)

erip
  • 16,374
  • 11
  • 66
  • 121
5

Is this something to do with const or const_cast?

Yes.

Even with const_cast, it's still undefined behavior to modify an object that was originally const. Or, in other words, it's illegal to use const_cast to write to a const object.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • I know. That's why I said it's illegal to *modify* / *write*. – Yu Hao May 05 '16 at 13:25
  • The way I see it is, if you did the cast but didn't do the write operation, that means the write access isn't given. So I don't see how that statement is false. It's quite possible that I was wrong though, as English is not my native language, so feel free to edit my answer any time. – Yu Hao May 05 '16 at 13:37