C Cast vs C++ Cast

What is the difference between using C cast:

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

For C++cast:

float t = 5.0f;
int v = static_cast<int>(t);
 2
Author: cYeR, 2017-10-06

2 answers

The static_cast of the C++ default is more restrictive and only allows conversions between supported types. This compatibility is validated at compile time:

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

cast in C style allows conversions between incompatible types without any type of verification:

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

The reinterpret_cast of the C++ pattern behaves identically to casts in the C style, allowing conversions between incompatible types:

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

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

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

 0
Author: Lacobus, 2017-10-06 14:29:18

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

In general the C++ engine is more secure and does not allow what should cause problems. The compiler plus the template engine can indicate whether there is compatibility between the types for the Cast to be successful.

In C it is even possible that some optimization eliminate cost of runtime , but at first it will be performed there.

Some people don't like the C style as well because it's not easy to search the code. Of course this is a bit of an Ides glitch.

There are variations of Cast in C++ each one more suitable than another, and you can even make a dynamic Cast if need be. This makes it more readable and demonstrates more the intention than you want, even if the end result is often the even.

C++documentation .

 1
Author: Maniero, 2017-10-06 12:55:06