Consider:
b = (int) a; // C-like cast notation
b = int (a); // Functional notation
C-style casts can be used to convert any type into any other type, potentially with unsafe results (such as casting an integer into a pointer type). (<type>)<value> This example casts an int to a double for the purpose of avoiding truncation due to integer division: double result = (double)4/5; Popular pages.
In short: static_cast<>() gives you a compile time checking ability, C-Style cast doesn't. static_cast<>() is more readable and can be spotted easily anywhere inside a C++ source code, C_Style cast is'nt. Intentions are conveyed much better using C++ casts.
2) The functional cast consists of a simple type specifier or a typedef specifier (in other words, a single-word type name: unsigned int(expression) or int*(expression) are not valid), followed by a single expression in parentheses. This cast is exactly equivalent to the corresponding C-style cast expression.
The C++ cast operators are keywords defined in the language. While they look like template functions, they are part of the language itself, i.e.the behavior is implemented in the compiler, not in the standard library.
Apparently I was wrong in my initial cut at an answer. They are roughly equivalent. And while compound type names like long long
or void *
can't use functional syntax directly (i.e. long long(val)
doesn't work), using typedef
can get around this issue.
Both cast notations are very bad and should be avoided. For example:
const char c = 'a';
void *fred = (void *)(&c);
works, and it shouldn't.
Both the C-style cast notation will sometimes behave like static_cast
, sometimes like const_cast
, sometimes like reinterpret_cast
, or even a combination of the two depending on the exact situation in which it's used. These semantics are rather complex and it's not always easy to tell exactly what's happening in any given situation.
I have gone to using mostly C++ static_cast<type>(val)
style casts, and never use C-style casts. Based on my research for this question I'm going to also stop using function-style casts for anything. The question "C++ cast syntax styles" has an excellent answer (the accepted one) that details why.
There's hardly any difference. Officially, the first tells the compiler that the value is an integer. This probably doesn't generate any extra code at all. The function call is an actual call that internally performs the other typecast. A smart compiler will optimize this, so they are actually the same.
There isn't any difference. It is a matter of preference. These are old-style casts.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With