const_cast

P

Podrzut_z_Laweczki

Hello everyone, I have a question:

const double zaq = 1.23;
const double *ptcd = &zaq;
double *ptd;
ptd = const_cast<double*>(ptcd);
*ptd = 5.67;
cout<<zaq<<endl;

It's only an exercise. I tried that in VS.NET 2003 and it seems to work
only with floating point types. I know it's not the best way, but I'm
just curious why this example doesn't work for other types.
 
H

Howard

Podrzut_z_Laweczki said:
Hello everyone, I have a question:

const double zaq = 1.23;
const double *ptcd = &zaq;
double *ptd;
ptd = const_cast<double*>(ptcd);
*ptd = 5.67;
cout<<zaq<<endl;

It's only an exercise. I tried that in VS.NET 2003 and it seems to work
only with floating point types. I know it's not the best way, but I'm
just curious why this example doesn't work for other types.

In what way does it "work"? It's not that this "isn't the best way", but
that it's just plain wrong. Using a trick to allow it to happen doesn't
make it legal. It's not. It is Undefined Behavior to change something
which you've declared as const. (Undefined Behavior means it may work, or
it may not; it may crash, or it may not; it _may_ do just about anything.)

-Howard
 
N

Noah Roberts

Podrzut_z_Laweczki said:
Hello everyone, I have a question:

const double zaq = 1.23;
const double *ptcd = &zaq;
double *ptd;
ptd = const_cast<double*>(ptcd);
*ptd = 5.67;
cout<<zaq<<endl;

It's only an exercise. I tried that in VS.NET 2003 and it seems to work
only with floating point types. I know it's not the best way, but I'm
just curious why this example doesn't work for other types.

Modification of a const object is always undefined. The behavior of
such undefined behavior is thus often times rather unpredictable and
undefined.
 
P

Podrzut_z_Laweczki

Howard said:
In what way does it "work"? It's not that this "isn't the best way", but
that it's just plain wrong. Using a trick to allow it to happen doesn't
make it legal. It's not. It is Undefined Behavior to change something
which you've declared as const. (Undefined Behavior means it may work, or
it may not; it may crash, or it may not; it _may_ do just about anything.)

I didn't intend to use that, but I get the picture now. Thank you.
 

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,792
Messages
2,569,639
Members
45,353
Latest member
RogerDoger

Latest Threads

Top