1

I was experimenting with const pointers.

#include <bits/stdc++.h>
using namespace std;
int main()
{
    const int i=4;
    const int *const p=&i;
    int *p1=const_cast<int*>(p);
    *p1=10;
    cout<<p<<" "<<p1<<" "<<&i<<endl;
    cout<<i<<" "<<*p1<<endl;
}

I know that using const_cast causes undefined behavior when the object in question is const(like i in this case). But after executing the code the value of i remains 4 and value of *p1 is 10 while the value of p p1 ans &i are the same, i.e , p1 is pointing to location of i but dereferencing it gives some other value. How does it happen?

Compiled with: g++ 4.8.1 and clang++ 3.3.

user2179293
  • 425
  • 9
  • 22
  • 4
    The variable appearing to have two values is a possible consequence of undefined behaviour – M.M Aug 10 '14 at 05:55
  • @MattMcNabb but the way *p works. It checks the memory location pointed to by p. It p1 indeed holds the address of i even after cast then shouldn't it just output the correct value of i. – user2179293 Aug 10 '14 at 06:01
  • @MattMcNabb Ok I got the answer http://stackoverflow.com/questions/3593687/two-different-values-at-the-same-memory-address?rq=1 . This question completely similar to my question(i dont know why this question didnt appear when i googled for it) – user2179293 Aug 10 '14 at 06:05
  • 2
    When something is undefined, it means undefined. – Rapptz Aug 10 '14 at 06:06
  • 1
    @user2179293 that seems to be a feature of SO, the "Related" links don't show up until after you post your question – M.M Aug 10 '14 at 06:09

1 Answers1

4

An attempt to modify an object declared as const triggers undefined behavior. The rest follows. "Same memory location storing two different values" is a perfectly normal manifestation of undefined behavior.

P.S. In practical reality the behavior you observe is caused by the simple fact that when you read the value of i, the compiled code does not even attempt to access its memory location. The compiler simply substituted 4 at compile time as the "already known" value of i. The compiler knows that the value of i cannot possibly ever change, so there's no point of actually reading it from memory. Even if you destroy the original value in memory (which is what you attempted to do), it will not have any effect on the actual code that directly "reads" i, since every occurrence of direct read access to i has already been replaced with literal 4 at compile time.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765