Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I use 'static_cast' for numeric casts in C++?

Tags:

c++

casting

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?

like image 306
peper0 Avatar asked Dec 21 '25 00:12

peper0


2 Answers

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:

  • you don't need to remember that C-style cast for numerics safely devolves to static_cast and never reaches reinterpret_cast - I'd call it "ease of use" and "no surprises" part
  • you can textually search for cast operations (grep 'static_cast<double>' vs grep '(double)' which can be part of function signature)
like image 76
Adam Kotwasinski Avatar answered Dec 22 '25 12:12

Adam Kotwasinski


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 a const_­cast,
  • a reinterpret_­cast, or
  • a reinterpret_­cast followed by a const_­cast,

can be performed using the cast notation of explicit type conversion.

[expr.cast/4]

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.

like image 39
Caleth Avatar answered Dec 22 '25 13:12

Caleth