Reputation: 53
In XCode I've tried to manipulate const int
value by using pointer. Here is the code:
const int con = 5;
int *p;
p = &con;
(*p) +=1;
printf("Add of constant:%p\n",&con);
printf("Add of pointer:%p\n",p);
printf("%d - %d",con,*p);
Result is like that on XCode:
Add of constant:0x7fff5fbff79c
Add of pointer:0x7fff5fbff79c
5 - 6
but on linux virtual machine values of con
and *p
is same 6
.
Why there is a difference between values on XCode?
Upvotes: 1
Views: 83
Reputation: 3183
Tried this with VisualStudio, get the same result as with XCode. Assembly listing proved @Gerhardh point:
(*p) +=1;
successfully increases value of con
in RAM printf("Add of constant:%p\n",&con);
prints address of this memory correctlyprintf("%d - %d",con,*p);
doesn't read con
value from RAM, but passes 5 directly into printf. Optimization threw away unnecessary read for value known at compile time. Here is related assembly listingprintf("%d - %d",con,*p);
mov eax,dword ptr [p] //get p
mov ecx,dword ptr [eax] //get *p
push ecx //push *p (3rd param)
push 5 //push 5 (2nd param). No read of con
push offset string "%d - %d" (415800h) //push addr of format string (1st param)
call dword ptr [__imp__printf (4182BCh)] //call printf()
Obviously, compiler on your VM didn't perform the same optimization.
Upvotes: 1