strange behaviour

M

Money

#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
 
H

Heinz Ozwirk

Money said:
#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

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

Heinz
 
J

John Carson

Money said:
#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

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.
 
R

Rolf Magnus

Money said:
#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

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top