-1
const int c= 7 ;
const int * b= &c ;
int *a = (int *)b ;
*a = 6; 
cout<<*a<<endl;
cout<<*b<<endl;
cout<<c<<endl;

I run it by g++ complier , and the output is : 6 6 7 I know it's inadvisable, but I am confused with it. I think the pointer b points to c , which is const , but why *b is changed to 6 while c is still equal to 7 ? they refer to the same stuff , why different?
could you explain how this code works internally ?

GuangshengZuo
  • 4,447
  • 21
  • 27

2 Answers2

4

§7.1.6.1 [dcl.type.cv]/p4:

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.

Undefined behavior means anything can happen. As far as the language is concerned, your program may appear to run correctly, may crash, may produce incorrect results, may chomp up your hard drive, or may blow up the planet.

In this particular case, it is likely that the compiler simply generated code that prints out 7 directly, assuming that c is 7, which it is allowed to do since c is const.

T.C.
  • 133,968
  • 17
  • 288
  • 421
2

The C-style cast (int *) performs a const_cast on b. Why this is bad has been explained plenty of times on SO.

Community
  • 1
  • 1
Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182