const_cast

Hi

i'm using const_cast to change the data of the constant variable. but on next while i'm trying to print the value its showing old data stored.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
 
using namespace std;
 
int main()
{
    const int a = 5;
 
    const_cast<int &>(a) = 6;
 
   cout << "Hello World " << a << endl; 
 
   return 0;
}


o/p : Hello World 5

why the value is getting changed again.?

Thanks
Modifying a const object engenders undefined behaviour.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

int main()
{
    const int i = 8 ;
    const int* p = &i ;
    std::cout << "int at address " << &i << " has value " << i << '\n'
              << "int at address " << p << " has value " << *p << "\n\n" ;

    const_cast<int&>(i) = 56  ; // **** UB
    std::cout << "int at address " << &i << " has value " << i << '\n'
              << "int at address " << p << " has value " << *p << "\n\n" ;

    *const_cast<int*>(p) = 99  ; // **** UB
    std::cout << "int at address " << &i << " has value " << i << '\n'
              << "int at address " << p << " has value " << *p << "\n\n" ;
}

clang++ -std=c++11 -stdlib=libc++ -O3 -Wall -Wextra -pedantic-errors main.cpp -lsupc++ && ./a.out
int at address 0x7fff178ac1f8 has value 8
int at address 0x7fff178ac1f8 has value 8

int at address 0x7fff178ac1f8 has value 8
int at address 0x7fff178ac1f8 has value 56

int at address 0x7fff178ac1f8 has value 8
int at address 0x7fff178ac1f8 has value 99

http://coliru.stacked-crooked.com/a/907b949e257c1913
Hi JLBorges

How come we have two values in same memory locations...?

Thanks
This is Undefined Behavior for you. When you trigger it, anything can happen, including formatting your hard drive and making demons to fly out of your nose. It is allowed for program to behave that way.

What probably happens is that all entry of i are replaced by 8 in compile time. Compiler can do that, as you declared variable to be constant, and therefore promised that it won't be ever changed.

If this variable would have static storage duration instead of automatic, it would be likely placed in read only memory and any attempt to change it would lead to crash.

So, in any situation, never change value of constant variable.
ok thanks MiiNIpaa
Topic archived. No new replies allowed.