1

I'm in the habit of doing 1. to coerce the code below into a floating point calculation but it just occurred to me: is there any difference in behaviour with 2.? It certainly looks less neater.

long blah = 3;

// 1

double d1 = 1 / static_cast<double>(blah);

// 2 note: not C-style (double) blah

double d2 = 1 / double(blah);

1 Answers1

4

Using a scalar type like a constructor, and the equivalent "C-style" cast syntax, is shorthand for static_cast, const_cast, and/or reinterpret_cast, whichever is needed. Since it's imprecise, it can mask an error.

In this case, and for all conversions between built-in numeric types, the C-style cast is the same as static_cast. Still, many C++ users (including me) consider it a bad habit even so.

Potatoswatter
  • 134,909
  • 25
  • 265
  • 421
  • 3
    See http://en.cppreference.com/w/cpp/language/explicit_cast for exact order of casts attempted. C-style casts use the first one of these that is successful. – patatahooligan Sep 16 '17 at 09:32