0

I tried running the following below:

#include<iostream>
using namespace std;

int main()
{
    const int a = 10;
    cout<<&a<<endl;
    
         // int* p = &a;  invalid conversion from const int* to int*
    
    int* q = (int*)&a;  // what is happening here?
    *q=20;
    
    cout<<q<<endl;
    cout<<*q<<endl<<a<<endl;
    return 0;
}

OUTPUT

0x6ffe14

0x6ffe14

20

10

If the address is same, why are results different?

Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52
  • 3
    Undefined Behaviour is undefined. You are not allowed to modify `const` variable, even if you cast constness away. – Yksisarvinen Jul 05 '21 at 16:33
  • `int* p = &a;` isn't allowed but `int* q = (int*)&a;` is allowed because the latter is a C-style cast, which will include a `reinterpret_cast`, which is a _very_ blunt instrument of you asserting to the compiler that regardless of what it thinks about the types, you have assurances that the conversion is valid. In this case the conversion actually isn't valid and you're getting undefined behavior. – Nathan Pierson Jul 05 '21 at 16:35
  • `what is happening here?` What happens there is an explicit conversion. By using a cast such as this, you're telling the compiler to ignore the type system and to do what you tell it to do whether it makes sense or not. It doesn't make sense, don't do it. `why are results different?` Because the behaviour of the program is undefined. It's a buggy program. – eerorika Jul 05 '21 at 16:36
  • If you can read assembly then go ahead. My money is that the compiler is assuming the pointers point to different objects. – Bathsheba Jul 05 '21 at 16:41
  • `int* q = (int*)&a; // what is happening here?` A programmer making a programming bug is happening here. – Eljay Jul 05 '21 at 16:44
  • 1
    The most likely cause is that the compiler saw that `a` is a `const` so generated assembly equivalent to `cout<<*q< – François Andrieux Jul 05 '21 at 16:45

0 Answers0