After reading here a lot of answers about C-style casting in C++ I still have one little question. Can I use C-style casting for built-in types like long x=(long)y;
or it's still considered bad and dangerous?
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.
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).
Static casts are only available in C++.
It helps maintain correctness, since static_cast cannot do some casts which a C-style cast can.
Can I use C-style casting for built-in types like long x=(long)y; or it's still considered bad and dangerous?
Don't use them, ever. The reasons against using them applies here as well. Basically, once you use them, all bets are off because the compiler won't help you any more. While this is more dangerous for pointers than for other types, it's potentially still dangerous and gives poor compiler diagnostics in the case of errors, whereas new style casts offer richer error messages since their usage is more constrained: Meyers cites the example of casting away const
ness: using any cast other than const_cast
won't compile, thus making it clear what happens here.
Also, some other disadvantages apply regardless of the types, namely syntactic considerations: A C-style cast is very unobtrusive. This isn't good: C++ casts stand out clearly in the code and point to potentially dangerous code. They can also easily be searched for in IDEs and text editors. Try searching for a C-style cast in a large code and you'll see how hard this is.
On the other hand, C-style casts offer no advantages over C++ casts so there's not even a trade-off to consider.
More generally, Scott Meyers advises to “Minimize casts” in Effective C++ (item 27), because “casts subvert the type system.”
I would not, for the following reasons:
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