views:

675

answers:

4
  int64_t a = 1234;

  double d = (double) a;

Is this the recommended way?

+4  A: 

You should use static_cast or rely on the implicit cast instead:

int64_t a = 1234;
double d = static_cast<double>(a);
double f = a;
strager
+4  A: 

use static_cast as strager answers. I recommend against using the implicit cast (or even a C-style cast in C++ source code) for a few reasons:

  • Implicit casts are a common source of compiler warnings, meaning you may be adding noise to the build (either now, or later when better warning flags are added).
  • The next maintenance programmer behind you will see an implicit cast, and needs to know if it was intentional behavior or a mistake/bug. Having that static_cast makes your intent immediately obvious.
  • static_cast and the other C++-style casts are easy for grep to handle.
Tom
On "intent": especially when the assignment is far from the declaration of d, static_cast<double> violates DRY. d = static_cast<typeof(d)>(a) is better in that respect, but then I lose the will to live and figure maybe d = a would be better after all ;-)
Steve Jessop
You're right that it violates DRY... but C++ as a language isn't DRY anyhow, if you consider forward declarations. Also, IIRC, typeof(d) requires RTTI and <typeinfo>, which isn't usable in some environments.
Tom
...though you're right... the DRY violation would cause some weird code if someone does an incomplete refactoring. float d; d = static_cast<double>(value); // WTF
Tom
+2  A: 

For POD types both versions do the same thing. Choose the one you prefer and be consistent.

I know many people who prefer the former for typing/readability and I tend to agree with this but I can live with either.

I've heard the "easy to grep for" argument many times but have yet to ever come across a situation where I've needed to grep my codebase for POD casts.

Andrew Grant
+1, I've never had to grep for casts either
Adam Rosenfield
+1  A: 

You can also use the conversion syntax, which is equivalent to a static_cast:

int64_t a = 1234;
double d = double(a);

This is a useful syntactic construction in that it allows primitive and class types to be treated the same way in template code, either doing a static_cast, for the primitive, or invoking a constructor, for the class type.

dcw