Click here to Skip to main content
15,898,881 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
When I tried below code I got strange results.I am trying to change value of constant by using the pointers.But when I output the results pointer value and the original variable variable value its giving two different values.Can anyone explain what exactly happens when explicit conversion take place?

C++
int main()
{
    int *p ;
    const int a = 20;
    p=(int *)&a;
    *p = *p +10;
    cout<<"p is"<<*p<<"\na is"<<a;
}

output:
p is 30 
a is 20
Posted
Updated 6-Jun-15 5:19am
v2
Comments
Ashish Tyagi 40 6-Jun-15 12:26pm    
Because you ignored a warning :-)

The C++ compiler have very strong optimization when dealing with const's. To spare time and space the optimizer never allocate any instance of a const int, but use to supply directly the value where it is requested in the more efficient way for that specific condition.
So when you ask for a pointer to a constant the compiler creates an instance of the constant value in memory (having a life scope compliant with the scope of the request) and pass the pointer of this constant to the piece of code that requested it.
In the successive part of your code where you ask for the constant value the compiler knows that is much more efficient to pass the value instead of to retrieve the value previously allocated.
Practically even if you modify the value accessed by pointer you cannot modify another instance of the value.
The C++ compiler treats the const values almost as a #define, but with more flexibility.
BTW your code is absolutely incorrect because you cannot modify a constant. The incorrect usage that you made exposed this side effect (it should be a bug, but C++ purists could shoot us if we make this affirmation :D).
 
Share this answer
 
v3
You are taking the address of a const int and then cast it to a non-const pointer. And you are wondering why the program is behaving strangely? ...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900