Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Please explain the Output .. (http://www.go4expert.com/forums/explain-output-t16347/)

raj_ksrt 26Feb2009 10:38

Please explain the Output ..
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.

xpi0t0s 26Feb2009 13:27

Re: Please explain the Output ..
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.

asadullah.ansari 2Mar2009 15:10

Re: Please explain the Output ..
Remember One thing...
If you cast away the constness of an object that has been explicitly declared as const, and attempt to modify it, the results are undefined, But compiler will allow to compile.
for more detail you can refer ...

All times are GMT +5.5. The time now is 18:04.