Luciano,

>   const int i2 = 2;
>   int& ri2 = (int&) i2;
>   ri2 = 102;  // should change the value of both 'i2' and 'ri2'

Should it, my friend?

As far as I'm concerned, ri2 is a reference type for an int, in this case const 
int i2 and it's correct the (int&) cast; if i2 weren't const, the cast wouldn't 
be necessary.

Such being, i2 should never change, retaining the initialized value of 2.

See there's nothing wrong with ri2 getting another value: it's not itself 
const; were ri2 const int& ri2 = (int&) i2, then the assignment ri2 = 102 would 
be impossible.

So, 102 affects ri2 only, but not i2, const.

Best, 

Geraldo


--- In [email protected], Luciano Cattani <xcianox2...@...> wrote:
>
> 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
>


Reply via email to