Connecting Tech Pros Worldwide Help | Site Map

strange behaviour

Money
Guest
 
Posts: n/a
#1: May 27 '06
#include<iostream>

int main()
{
int const x=0;
int *y = (int*)&x;
*y = 20;
cout<<" y:"<<*y;
cout<<"x: "<<x;
}

It gave me y=20 and x=0....but isn't y pointing to x

Heinz Ozwirk
Guest
 
Posts: n/a
#2: May 27 '06

re: strange behaviour


"Money" <spicymonchi@gmail.com> schrieb im Newsbeitrag
news:1148724462.984291.45490@j33g2000cwa.googlegro ups.com...[color=blue]
> #include<iostream>
>
> int main()
> {
> int const x=0;
> int *y = (int*)&x;
> *y = 20;
> cout<<" y:"<<*y;
> cout<<"x: "<<x;
> }
>
> It gave me y=20 and x=0....but isn't y pointing to x[/color]

.... but isn't x const? Casting away const results in undefined behaviour,
and whoever tries to do so, deserves whatever he gets.

Heinz

John Carson
Guest
 
Posts: n/a
#3: May 27 '06

re: strange behaviour


"Money" <spicymonchi@gmail.com> wrote in message
news:1148724462.984291.45490@j33g2000cwa.googlegro ups.com[color=blue]
> #include<iostream>
>
> int main()
> {
> int const x=0;
> int *y = (int*)&x;
> *y = 20;
> cout<<" y:"<<*y;
> cout<<"x: "<<x;
> }
>
> It gave me y=20 and x=0....but isn't y pointing to x[/color]

Attempting to modify a const value is undefined behaviour --- anything could
happen.

At a guess, I would say that what does happen is that the compiler replaces
x everywhere by 0 --- since x is const, it always has to equal 0 so why
shouldn't the compiler do this? Your code does successfully modify the value
stored in the memory allocated for the x variable, but the compiler never
looks up this value when processing an x in the code.

--
John Carson


Rolf Magnus
Guest
 
Posts: n/a
#4: May 27 '06

re: strange behaviour


Money wrote:
[color=blue]
> #include<iostream>
>
> int main()
> {
> int const x=0;
> int *y = (int*)&x;
> *y = 20;
> cout<<" y:"<<*y;
> cout<<"x: "<<x;
> }
>
> It gave me y=20 and x=0....but isn't y pointing to x[/color]

What exactly are you trying to accomplish with this? By making x const, you
promised to the compiler that it won't be modified, and the compiler will
rely on this and probably do some optimizations that can only be done with
constants. The compiler can ensure that you don't modify it as long as you
don't cast away the constness. As yoon as you do that cast, it's your
responsibility to ensure that you never try to modify it.

Oh, and btw: Avoid C style cast. Better use the safer C++ casts.

Closed Thread