1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

Please explain the Output ..

Discussion in 'C' started by raj_ksrt, Feb 26, 2009.

  1. raj_ksrt

    raj_ksrt New Member

    Hi all,

    I am executing the following code.
    int main()
        const int i=10;
        int *j= const_cast<int *>(&i);
        *((int *)&i)=20;
        printf("%d %d",*(&i),*j);
        printf("\n%x %x",&i,j);
        return 0;
    I observe the output as 10 20.The addresses of i and j are same but their values are different. How can this be possible?

    Please provide some explanation.
  2. xpi0t0s

    xpi0t0s Mentor

    It's undefined behaviour because you're modifying a constant.

    It's up to the compiler of course, but one way to implement consts is as a typed #define and wherever it sees "i" referenced it just replaces it with a typecheck and the value 10 (and it could also exist in memory in case anyone wants to take its address). And you're not going to fool a compiler with *(&i) - it knows these are inverse operations of each other so this is directly equivalent to i, which is 10 (because i is a const).

    Looking at the generated assembly answers all. This is from Visual Studio 2005:
        printf("%d %d\n",*(&i),*j);
    00411762  mov         esi,esp 
    00411764  mov         eax,dword ptr [j] 
    00411767  mov         ecx,dword ptr [eax] 
    00411769  push        ecx  
    0041176A  push        0Ah  
    0041176C  push        offset string "%d %d\n" (41CB8Ch) 
    00411771  call        dword ptr [__imp__printf (4204A4h)] 
    and you can see at 0041176A that the literal value 10 is pushed onto the stack, NOT what is in memory at &i.
  3. asadullah.ansari

    asadullah.ansari TechCake

    Last edited: Mar 2, 2009

Share This Page