--- In [email protected], "py2akv" <g...@...> wrote:
>
> 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.

But ri2 is a reference to i2. So whether i2=2 or i2=102, I would expect ri2=i2.

In fact if you modify the printfs to output the variable addresses as well:

  printf("i2=%d %p\n", i2, &i2 );  // = 2 (???)
  printf("ri2=%d %p\n", ri2, &ri2 );  // = 102 (OK)

I get (g++ under linux):

i2=2 0xbf95a1a8
ri2=102 0xbf95a1a8

This appears to show different values at the same address.

I suspect that because you are using a cast to overwrite a const value the 
behaviour is undefined. However I'm curious to know what's actually happening - 
optimisation perhaps?

However I'm only a C programmer, so apologies if I'm missing something obvious.

Reply via email to