1

http://www.ideone.com/kRaMj

I found this in the algogeeks forum. Can anyone explain how value of i is still 0, but *p shows 2 although their addresses are the same.

#include<stdio.h>

int main() 
{
    const int i = 0;
    int * p ;
    p = (int *) & i;
    *p = 2;

    printf("(i,p): %x %x \n",&i,p);
    printf("(i,p): %d %d \n",i,*p);
}

The output of the program is:

(i,p): bfdf6234 bfdf6234 
(i,p): 0 2 
Alok Save
  • 202,538
  • 53
  • 430
  • 533
Nikhil
  • 355
  • 2
  • 4
  • 5
  • Please include the code in the question instead of posting a link – Andreas Brinck Aug 21 '11 at 15:59
  • @Nikhil: Please try to keep the Q/Answers **self contained**, It is good that you posted the link to code on Ideone here but do replicate it here as well, The reason being if for some reason that link becomes invalid in future, the Q will still be valid and answers on it will help someone else. – Alok Save Aug 21 '11 at 16:07
  • Sorry about posting the link and not the actual code. Will keep that in mind for future posts. – Nikhil Aug 22 '11 at 06:02

1 Answers1

9

That code is causing an Undefined Behavior.
Once you change the value of the constant variable i using a pointer to it p, all bets are off and any behavior might be seen.

Undefined behavior means anything can happen and the behavior cannot be explained as the Standard, which defines the rules of the language does not define any behavior.

Rudy Velthuis
  • 28,387
  • 5
  • 46
  • 94
Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • 3
    True enough. Although in this case, obviously the compiler is assuming you do not modify the `const` int and is simply propagating the constant 0 into the `printf`. – Nemo Aug 21 '11 at 15:58