Jump to content
  • Advertisement

Archived

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

Snyper

more on casting

This topic is 6542 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
Advertisement
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

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!