Is it OK to use C-style cast for built-in types?

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 constness: 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.”

Leave a Comment