Archived

This topic is now archived and is closed to further replies.

Snyper

more on casting

Recommended Posts

Snyper    122
What is the difference between these two ways to cast. 1st: float x = 5.4f; int y = 0; y = (int)x; 2nd: float x = 5.4f; int y = 0; y = static_cast(x); I read in this c++ tutorial thing that comes w/ MS VC++ 6.0 and it says the static_cast is a ''better'' way of casting as the old way, (int)x, is error prone? Why is that?

Share this post


Link to post
Share on other sites
mossmoss    326
quote:
Original post by Snyper

What is the difference between these two ways to cast.

1st:

float x = 5.4f;
int y = 0;

y = (int)x;

2nd:

float x = 5.4f;
int y = 0;

y = static_cast(x);

I read in this c++ tutorial thing that comes w/ MS VC++ 6.0 and it says the static_cast is a ''better'' way of casting as the old way, (int)x, is error prone? Why is that?



In the generated code, there should be no difference.

The reason the static_cast<int>(x) is "better" is for sanity sake. The compiler, with these casts, can perform extra checks for you. It''s a way to restrict your actions and create safer code, besides being immediately readable and self-documenting in the source code.

There are four new-style C++ casts:

const_cast
static_cast
dynamic_cast
reinterpret_cast

Each has a particular use. const_cast only lets you change the const-ness or volatile-ness of the type. reinterpret_cast will change any pointer type into any other pointer type, or pointers to/from integers. static_cast and dynamic_cast are similar, the difference being that static_cast is checked at compile type while dynamic_cast is checked at run-time.


---- --- -- -
Blue programmer needs food badly. Blue programmer is about to die!

Share this post


Link to post
Share on other sites