1

My problem is, why first part of the code does not work while the second one works. Non-const pointer should modify the const value using the const_cast previously but with integers this trick does not work. Could you explain why that happens?

const int i = 5;
cout << i << endl; //output: 5
int *ptr_i = const_cast<int*>(&i);
*ptr_i = 100;
cout << i << endl; //output : 5

const double d = 5;
cout << d << endl; //output : 5
double *ptr_d = const_cast<double*>(&d);
*ptr_d = 100.; 
cout << d << endl; //output : 100
Tomker
  • 27
  • 1
  • 5
    Attempting to modify a constant variable leads to [*undefined behavior*](http://en.wikipedia.org/wiki/Undefined_behavior), and undefined behavior makes your whole program ill-formed and invalid. – Some programmer dude Mar 30 '15 at 10:54
  • You are calling undefined behavior, so none of these casts is supposed _to work_. – πάντα ῥεῖ Mar 30 '15 at 10:55
  • And note that when you have Undefined Behaviour, anything at all can happen, including *appearing* to work in one case and not in the other. – BoBTFish Mar 30 '15 at 10:55
  • I think the trick is compiler doesn't expect that const value will be changed (as other commenters noted it is Undefined behavior) and optimizes out direct reading of `i` second time. Changing type qualifiers to `volatile const` hints compiler that constant is mutable and everything seems to be fine after that. – myaut Mar 30 '15 at 10:56
  • 2
    @myaut "**seems to be** fine". Exactly. UB will do that sometimes. It's still wrong though. – BoBTFish Mar 30 '15 at 10:58
  • 1
    The most awkward thing is that i have tried it few times using various situations and every single time const_cast for doubles worked perfectly fine. Never for int. Anyway, thanks for answers. I will remember that it's "undefined behavior". – Tomker Mar 30 '15 at 11:14
  • See also http://stackoverflow.com/questions/22391423/weird-behaviour-with-const-cast – M.M May 05 '16 at 13:23

2 Answers2

5

Modifying a const variable is undefined behaviour:

n4296 §7.1.6.1/4

Except that any class member declared mutable (7.1.1) can be modified, any attempt to modify a const object during its lifetime (3.8) results in undefined behavior.

const_cast is generally for communicating with non-const-correct APIs or casting away volatile qualifiers; it shouldn't be used like this.

TartanLlama
  • 63,752
  • 13
  • 157
  • 193
2

Non-const pointer should modify the const value using the const_cast previously but with integers this trick does not work.

No, non-const pointer modifying the const value is undefined behavior. It is not supposed to work.

Could you explain why that happens?

Since this is UB, the compiler is free to do anything at all here, and "anything at all" means the code will happen to work in the case of int only (at least, for your compiler).

TLDR: undefined behavior is undefined.

utnapistim
  • 26,809
  • 3
  • 46
  • 82