A question related to Regular cast vs. static_cast vs. dynamic_cast:
What cast syntax style do you prefer in C++?
(int)foo
static_cast<int>(foo)
int(foo)
They may not translate to exactly the same instructions (do they?) but their effect should be the same (right?).
If you're just casting between the built-in numeric types, I find C++-style cast syntax too verbose. As a former Java coder I tend to use C-style cast syntax instead, but my local C++ guru insists on using constructor syntax.
What do you think?
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.
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.
Static casts are only available in C++. Static casts can be used to convert one type into another, but should not be used for to cast away const-ness or to cast between non-pointer and pointer types.
It's best practice never to use C-style casts for three main reasons:
As palm3D noted:
I find C++-style cast syntax too verbose.
This is intentional, for the reasons given above.
The constructor syntax (official name: function-style cast) is semantically the same as the C-style cast and should be avoided as well (except for variable initializations on declaration), for the same reasons. It is debatable whether this should be true even for types that define custom constructors but in Effective C++, Meyers argues that even in those cases you should refrain from using them. To illustrate:
void f(auto_ptr<int> x); f(static_cast<auto_ptr<int> >(new int(5))); // GOOD f(auto_ptr<int>(new int(5)); // BAD
The static_cast
here will actually call the auto_ptr
constructor.
According to Stroustrup:
The "new-style casts" were introduced to give programmers a chance to state their intentions more clearly and for the compiler to catch more errors.
So really, its for safety as it does extra compile-time checking.
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