-2

I have a piece of program as shown below:

#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
    const int i = 100;
    cout<<"const i::"<<i<<endl;
    const_cast<int&>(i) = 200;
    cout<<"const i after cast::"<<i<<endl;
    return EXIT_SUCCESS;
}

But the value of i is still 100. Aren't const_cast supposed to change the value of i?

anilLuwang
  • 25
  • 4
  • 1
    This is [undefined behavior to attempt to modify a const](http://stackoverflow.com/q/22656734/1708801) – Shafik Yaghmour Sep 16 '14 at 17:07
  • 1
    I'm gonna go out on a limb here and say a constant, by definition, cannot be changed. It's constant. – durbnpoisn Sep 16 '14 at 17:08
  • Because trying to do so is undefined behavior (but I'm willing to bet that this is a duplicate). – James Kanze Sep 16 '14 at 17:08
  • 1
    "Aren't `const_cast` supposed to change the value of `i`?" No. It allows you to change a non-constant value if you've only got a constant reference to it; but nothing is supposed to change a constant value. It wouldn't be constant otherwise. – Mike Seymour Sep 16 '14 at 17:10

1 Answers1

4

Constant data is, by its very definition, constant, and attempting to change constant data leads to undefined behavior.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621