A question related to Regular cast vs. static_cast vs. dynamic_cast:
What cast syntax style do you prefer in C++?
- C-style cast syntax:
(int)foo
- C++-style cast syntax:
static_cast<int>(foo)
- constructor syntax:
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?
Definitely C++-style. The extra typing will help prevent you from casting when you shouldn't :-)
Regarding this subject, I'm following the recommandations made by Scott Meyers (More Effective C++, Item 2 : Prefer C++-style casts).
I agree that C++ style cast are verbose, but that's what I like about them : they are very easy to spot, and they make the code easier to read (which is more important than writing).
They also force you to think about what kind of cast you need, and to chose the right one, reducing the risk of mistakes. They will also help you detecting errors at compile time instead at runtime.
We currently use C-style casts everywhere. I asked the other casting question, and I now see the advantage of using static_cast instead, if for no other reason than it's "greppable" (I like that term). I will probably start using that.
I don't like the C++ style; it looks too much like a function call.
I use static_cast for two reasons.
C-style cast is the worst way to go. It's harder to see, ungreppable, conflates different actions that should not be conflated, and can't do everything that C++-style casts can do. They really should have removed C-style casts from the language.
C-style cast syntax, do not error check. C++-style cast syntax, does some checking. When using static_cast, even if it doesn't do checking, at least you know you should be carefull here.