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?
According to Stroustrup:
So really, its for safety as it does extra compile-time checking.
The constructor syntax. C++ is OO, constructors exist, I use them. If you feel the need to annotate these conversion ctor's you should do it for every type, not just the built-in ones. Maybe you use the 'explicit' keyword for conversion ctors but the client syntax mimics exactly what the ctor syntax for built-in types does. Being greppable, that may be true, but what a big surprise that typing more characters makes searches easy. Why treat these ones as special? If you are writing math formulas with lots of int/unsigned/... to and from double/float - graphics - and you need to write a static_cast every time, the look of the formula gets cluttered and is very much unreadable. And it's an uphill battle anyway as a lot of times you will convert without even noticing that you are. For downcasting pointers I do use the static_cast as of course no ctor exists by default that would do that.
It's best practice never to use C-style casts for three main reasons:
As palm3D noted:
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:
The
static_cast
here will actually call theauto_ptr
constructor.Go for C++ style and, at worse, the ugly verbose code snippets that comprised C++'s explicit typecast will be a constant reminder of what we all know (i.e explicit casting is bad -- the lead to the coin-ing of expletives). Do not go with C++ style if you want to master the art of tracking runtime errors.