Reputation: 3223
Sometimes, we need to explicitly cast one numeric type to another (e.g. to avoid warning when we lose precision or range). For some:
double foo;
we could write:
(float)foo
but most C++ programmers say it's evil 'old-style cast' and you should use the 'new-style cast':
static_cast<float>(foo)
There is an alternative of boost::numeric_cast
which is quite interesting (at least in not-performance-critical code) but this question is about static_cast
.
A similar question was already asked, but the most important arguments used there are not valid for numerical cast (in my opinion, am I wrong?). There are they:
You have to explicitly tell the compiler what you want to do. Is it upcast, or downcast? Maybe reinterpret cast?
No. It is simple numeric cast. There is no ambiguity. If I know how static_cast<float>
works, I know how does it work for 'old-style' cast.
When you write (T)foo
you don't know what T
is!
I'm not writting (T)foo
but (float)foo
. I know what is float
.
Are there any important reasons for using a new, better casts for numeric types?
Upvotes: 3
Views: 1524
Reputation: 62676
Like many things inherited from C, the more specific C++ variants are there to inform readers of the code, not the compiler.
You use static_cast<double>
because it doesn't do all the things that (double)
can.
The conversions performed by
- a
const_cast
,- a
static_cast
,- a
static_cast
followed by aconst_cast
,- a
reinterpret_cast
, or- a
reinterpret_cast
followed by aconst_cast
,can be performed using the cast notation of explicit type conversion.
Specifying static_cast
alerts you with a compile time error, rather than silently having undefined behaviour, if the expression you think is safe isn't.
Upvotes: 1
Reputation: 4554
In a general scenario (which you have mentioned) you'd want explicit C++ cast to avoid possible issues mentioned in When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used? (ability to devolve into reinterpret_cast
).
In numeric scenario you get two benefits at least:
static_cast
and never reaches reinterpret_cast
- I'd call it "ease of use" and "no surprises" partgrep 'static_cast<double>'
vs grep '(double)'
which can be part of function signature)Upvotes: 1