12

Possible Duplicate:
Regular cast vs. static_cast vs. dynamic_cast
In C++, why use static_cast<int>(x) instead of (int)x?

What is the difference between static_cast<float>(foo) and float(foo)? I often see static_cast<float> or similar in template code to get from any integral type to some specific integral type. For example say I wanted a function to perform floating point division on any integral type. I normally see something like this:

template <typename T>
float float_div(T lhs, T rhs)
{
    // I normally see this
    return static_cast<float>(lhs) / static_cast<float>(rhs);

    // But I could do this
    // return float(lhs) / float(rhs); // But I could do this
}

Is there any advantage to using float(lhs) or static_cast<float>(lhs)? Also what is the name of the float(lhs) initialization/conversion?

Community
  • 1
  • 1
David Brown
  • 13,336
  • 4
  • 38
  • 55
  • 2
    `static_cast` stands out and shouts, "I AM PERFORMING A CAST!". – chris Jun 26 '12 at 18:03
  • 7
    @chris: At least until it runs out of mana. – Cat Plus Plus Jun 26 '12 at 18:04
  • Added question: any difference to `(float) foo`? – Lukas Schmelzeisen Jun 26 '12 at 18:07
  • 4
    @LukasSchmelzeisen: `(float)foo` and `float(foo)` are the same. – Cat Plus Plus Jun 26 '12 at 18:07
  • @LukasSchmelzeisen, That's an ill-advised C-style cast. I'm not sure if `float(foo)` and `(float)foo` are exactly the same, or have a subtle difference, but the C++ one is explicit, noticeable, and safer. – chris Jun 26 '12 at 18:08
  • @Cat Ah, I didn't realize this was just a C-style cast. – David Brown Jun 26 '12 at 18:15
  • FWIW, the official name in the C++ standard for a C-style cast is "Explicit Type Conversion (cast notation) [5.4]" and the float(lhs) variant is "Explicit Type Conversion (functional notation) [5.2.3]". They are basically equivalent to automatically doing of const_cast<> and/or static_cast<> and/or reinterpret_cast<> required to whack the source type into the target type. – Anders Nov 26 '15 at 07:33
  • @chris I don't think it is always ill-advised, especially with simple types. In pure C++, I agree but there are lots of places where integration with C and/or embedded OS's where the hard "just do it" casts are the least bad option. – Anders Nov 26 '15 at 07:40

0 Answers0