Author
Topic: When to use static_cast instead of original (cast) syntax in C++ (Read 216 times)

Hey everyone. I had another question about C++. So they introduced static_cast<type>, dynamic_cast<type>, etc to the language. The examples I see typically use the new casts when casting a class that is pointed to into its base class, but not for casting C++ built in types such as int, char, float, etc.

Is the current preffered method to use the original type casting provided with the language for built in types or now use static_cast<type> instead?

In the example below, GetNumberOfPackedFiles() returns an int value. However, i will be used to reference a location in a C++ container that uses size_t for storage position.

The old style casts are considered bad form now, though I've tended to stick with them due to the compact syntax. The new cast style is a bit more verbose, though that is intentional. It's best to avoid casts when you can. If you can't avoid them, then at least make it easy to search for them. (Try using a text search for the old style cast). It helps with hunting down bugs, since casts are ways of defeating the type checking system, and so a good source for errors. Splitting the old cast style into distinct new style casts also makes sure you're doing the minimum and intended conversion operation, rather than conflating a bunch of different things with one syntax.

The next step will be to learn the differences between the new style casts.

Thanks Hooman. In OP2Archive and OP2Utility, I pulled out all the older style casts and replaced them with static_cast. Only about 5 of them existed that I could find. Good idea on using the find command in VS to locate them.

Only about 5 of them existed that I could find. Good idea on using the find command in VS to locate them.

Yeah, problem with looking for the old style casts with text search, is the pattern you'd have to search for will likely match: function definitions, function calls, expressions with parenthesis, and casts

For a large project, that's a whole lot of extra fluff to search through just to find a few hopefully rare casts.