Skip to contentSkip to conversation

constant variable

DISCUSSION Nasir Simbolon 2 participants 2 messages Mar 11, 2004

lore
Share & tools
lore
#0 lore raw

Hi All,
I just curious. I have the following codes

main()
{
const int i=9; //declare constant integer variable and initialize
int* j=NULL; //declare a pointer to integer
j = (int*) &i; //j point to address of memory i
*j = 3; //modify value of j point to

	//Now print the result
	 printf("value of i = %d\n",i);
  	 printf("value of j = %d\n",*j);
	 printf("Address of i = %x\n",&i);

printf("Address of j = %x\n",j);
}
when I compile using gcc version 3.3.2 (Debian) and run, I have the result :

value of i = 9
value of *j = 3
Address of i = bffff8a4
Address of j = bffff8a4

Now, I notice that j point to address of i BUT they do not have the same value.

Anybody have an explanation?

Regards,

Nasir

Signature · 1 line
"timor Domini principium scientia (Prov 1:7)"
#1 lore raw
Quoted 5 lines
 	const int i=9;
     	int* j=NULL;
	 j = (int*) &i;

*j = 3;

Quoted 7 lines

when I compile using gcc version 3.3.2 (Debian) and run, I have the result :

value of i = 9
value of *j = 3

Now, I notice that j point to address of i BUT they do not have the same value.

Probably because of compiler optimisations. If you've specified that something is const, then the compiler is perfectly at liberty to assume that it is. This means that it can assume the initial value of i still applies, and so, rather than going to memory for i, it can just substitute the constant 9 in. This is likely to be much quicker at run time.

I can only reproduce this behaviour if I have compiler optimisations turned on, which adds some more weight to the explanation.

Steven.