Please explain the Output ..

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

  1. raj_ksrt

    raj_ksrt New Member

    Joined:
    Feb 26, 2009
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    Hi all,

    I am executing the following code.
    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.
    Sarma.
     
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    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:
    Code:
        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

    Joined:
    Jan 9, 2008
    Messages:
    356
    Likes Received:
    14
    Trophy Points:
    0
    Occupation:
    Developer
    Location:
    NOIDA
    Last edited: Mar 2, 2009

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice