Quote:
Originally Posted by en_7123 View Post
Well I think the compiler might throw a warning in the above code but still would give output 10 20.
There's nothing like actually trying it out. Visual Studio 2008 throws the error:
error C2440: 'initializing' : cannot convert from 'const int *' to 'int *'

A cast will fix that:
Code:
void test19()
{
	const int i=10;
	printf("%d\n",i);
	int *j=(int*)&i;
	*j*=2;
	printf("%d\n",i);
}
and running this, the output is:

10
10
Press any key to continue . . .

So even in debug mode the int i is optimised out, and we can see this in the generated assembly:
Code:
	const int i=10;
012516BE  mov         dword ptr [i],0Ah 
	printf("%d\n",i);
012516C5  mov         esi,esp 
012516C7  push        0Ah 
012516C9  push        offset string "%d %c" (1259800h) 
012516CE  call        dword ptr [__imp__printf (125D470h)] 
012516D4  add         esp,8 
012516D7  cmp         esi,esp 
012516D9  call        @ILT+610(__RTC_CheckEsp) (1251267h) 
	int *j=(int*)&i;
012516DE  lea         eax,[i] 
012516E1  mov         dword ptr [j],eax 
	*j*=2;
012516E4  mov         eax,dword ptr [j] 
012516E7  mov         ecx,dword ptr [eax] 
012516E9  shl         ecx,1 
012516EB  mov         edx,dword ptr [j] 
012516EE  mov         dword ptr [edx],ecx 
	printf("%d\n",i);
012516F0  mov         esi,esp 
012516F2  push        0Ah 
012516F4  push        offset string "%d %c" (1259800h) 
012516F9  call        dword ptr [__imp__printf (125D470h)]
and you can see at "012516C7 push 0Ah" and "012516F2 push 0Ah" that the literal value 10 is pushed, not the contents of memory location &i. So at the second printf, 10 is still pushed, not what j is pointing at.

Quote:
Code:
const int i=10;
printf("%d",i);
int j=i;
j*=2;
printf("%d",j);
How is the above code relevant to changing the value of const .In case you need to change the value of const(even though if that is the case no use of defining the variable as a const) you could only do it with pointer.The above code merely prints.
Precisely. That's why I said "do this INSTEAD". i.e. don't change the const variable with a pointer, cos you won't get the desired result. This way you DO get the desired result, i.e. the output 10 20, and just to be certain (in VS2008 at least):
Code:
void test19a()
{
	const int i=10;
	printf("%d\n",i);
	int j=i;
	j*=2;
	printf("%d\n",j);
}
Output:
10
20
Press any key to continue . . .