C Cast vs C++ Cast

Asked

Viewed 307 times

3

What’s the difference between using the C cast:

float t = 5.0f;
int v = (int)t;

For the cast of C++:

float t = 5.0f;
int v = static_cast<int>(t);

2 answers

2

There is a fundamental difference since, as the name says, cast C++ is static, meaning it is done at compile time, there is no external cost and can produce an error before generating the executable.

Generally speaking, the C++ engine is more secure and does not allow for what should cause problems. The compiler plus the C++ engine template can indicate if there is compatibility between types for the cast be successful.

In C it is even possible that some optimization eliminates cost of Runtime, but at first it will be held there.

Some people do not like the style of C either because it is not easy to search in the code. Of course this is a bit of a failure of Ides.

There are variations of cast in C++ each more suitable than another, and may even make one cast dynamic, if necessary. This makes it more readable and demonstrates the intention more than you want, even if the final result is often the same.

Documentation of the C++.

1


The static_cast of the pattern C++ is more restrictive and only allows conversions between compatible types. This compatibility is validated at build time:

char c = 123;
int * p = static_cast<int*>(&c); // Erro em tempo de compilação! 

The cast in the style C allows conversions between incompatible type without any kind of verification:

char c = 123;
int * p = (int*) &c;  // OK!

The reinterpret_cast of the pattern C++ behaves in the same way as castsin the style C, allowing conversions between incompatible types:

char c = 123;
int * p = reinterpret_cast<int*>(&c); // Conversão forçada: OK!

Avoid using casts in style C if you are using a compiler C++, always try to replace it with a static_cast, when possible.

And if the intention is really a forced conversion of types, use reinterpret_cast.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.