1

While I assign a const int to simple int pointer (via type casting), and then changed value of pointer. Now pointer giving me updated value but const int giving the same! Can anybody please explain what is going on here?

Here is sample code:

int main() {
    const int val = 5;
    int *p = (int*)&val;
    cout<<"val: "<<val<<endl;
    cout<<"*p: "<<*p<<endl;
    *p = 64;
    cout<<"*p: "<<*p<<endl;
    cout<<"val: "<<val<<endl;

    cout<<"p: "<<p<<endl;
    cout<<"&val: "<<&val<<endl;

    int *p1 = (int*)&val;
    cout<<"*p1: "<<*p1<<endl;

    const int *p2 = &val;
    cout<<"*p2: "<<*p2<<endl;

    return 0;
}

Here is the output:

val: 5
*p: 5
*p: 64
val: 5
p: 0x7ffcb2de795c
&val: 0x7ffcb2de795c
*p1: 64
*p2: 64

Here main point is, address stored in "p" is same as address of "val". Also any later pointer we are assigning (even const int *) reflecting changed value not original one.

dplank
  • 91
  • 8
  • 1
    What's going on here is "undefined behavior". – Sam Varshavchik May 27 '18 at 21:06
  • Then how undefined behavior giving defined values for p1 and p2? – dplank May 27 '18 at 21:27
  • 1
    @Sam - Forgive my ignorance. Why does the C++ standard give us `const_cast` if casting away const-ness is UB? Maybe the only thing we are allowed to do is cast to a `const` as a hint to the compiler (which probably violates aliasing rules)? If that is the case, then why does the standard not say it? Why doesn't casting away const-ness produce a compile warning or error? – jww May 27 '18 at 21:37
  • @jww - casting away constness is not necessarily undefined behavior. For example, casting away constness, but never modifying the really-const object. – Sam Varshavchik May 27 '18 at 22:28
  • I think this can be explained by the fact that the compiler is quite entitled to think that the contents of `val` never change (because you declared it `const`) and therefore optimises `cout << val` at line 8 to emit `cout << 5`. If I was the compiler, that's what I would do. Try `cout << * (int *) &val`. That might work (for some definition of 'work'). – Paul Sanders May 28 '18 at 14:10

0 Answers0