C Cast vs C ++ Cast

2

What is the difference between using the cast of C:

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

For the C ++ cast:

float t = 5.0f;
int v = static_cast<int>(t);
    
asked by anonymous 06.10.2017 / 14:34

2 answers

0

The static_cast of the default C++ is more restrictive and only allows conversions between compatible 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 style C allows incompatible conversions between 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 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 style C if you are using a C++ compiler, always try to replace it with a static_cast , when possible.

And if the attempt is actually a forced type conversion, use reinterpret_cast .

    
06.10.2017 / 16:29
1

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

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

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

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

There are cast variations in C ++ each more suited than others, and can even do a dynamic cast if needed. This makes it more readable and shows more intent than you want, although the end result is often the same.

C ++ Documentation .

    
06.10.2017 / 14:55