Hi all,
I tried the following code fragment on MS VC++ Express 2008:
int _tmain(int argc, _TCHAR* argv[])
{
// a static const integer
static const int i1 = 1;
int& ri1 = (int&) i1;
// ri1 = 101; ERROR: access violation
// a const integer declared on the stack
const int i2 = 2;
int& ri2 = (int&) i2;
ri2 = 102; // should change the value of both 'i2' and 'ri2'
printf("i1=%d\n", i1 ); // = 1 OK
printf("i2=%d\n", i2 ); // = 2 (???)
printf("ri2=%d\n", ri2 ); // = 102 (OK)
return 0;
}
The first lines are clear:
{
static const int i1 = 1;
int& ri1 = (int&) i1;
// ri1 = 101; ERROR: access violation
the code compiles if 'const int' is explicitly casted to a 'int&' variable but
when the app is exectued I got a 'memory access violation'.
OK, this is clear: static const data are stored in the code segment, which is
read-only.
Now the part I cannot understand: the second const int is declared on the stack
which is surely writable:
const int i2 = 2;
int& ri2 = (int&) i2; // an explicit cast is needed
ri2 = 102;
The code compiles and executes, but.... the output of 'i2' is 2 and the output
of 'ri2' (which is the same memory area) is 102.
I run the program in the integrated debugger and single-stepped until the
following line, watching the value of all variables:
ri2 = 102;
well, when this line is executed _both_ 'i2' and 'ri2' became 102!
The output of the printf() function is really a rebus for me.
Regards
Luciano