This question is a little subjective, but I believe it may lead to some constructive answers. Assume I have char x;
and I want to promote it to an integral so I can access it's numeric value. Which should I prefer to use and why? static_cast<int>
or unary arithmetic operator +
?
My own thoughts are that using a static_cast<int>
is more explicit and readable. However, using the unary arithmetic operator +
is shorter code.
Is one way safer than the other?
IMO, there is one important advantage of using static_cast
, even if it is a little bit more verbose: it allows you to quickly search your code for casts via grep
or any other text searching utility. In large projects this may make the difference, since otherwise C-style casts are often mistakenly matched in functions declarations such as void f(double)
, where (double)
is of course not a cast.
Moreover, static_cast
makes perfectly clear your intention. Using the +
operator may seem exotic (incomprehensible) to someone who is not 100% familiar with integer promotions rules. In terms of "safety", afaik, both are equally good.
Related: What is the difference between static_cast<> and C style casting?