1

I've seen these two different ways to cast an int to a double in C:

double double_var = (double) int_var;
double double_var = double(int_var);

What's the difference between these two methods? When should I use one over the other?

Ben Lindsay
  • 1,686
  • 4
  • 23
  • 44
  • 4
    One is valid C, the other isn't. Neither is necessary, since `double double_var = int_var;` already has the desired behaviour. – Kerrek SB Feb 02 '16 at 01:38
  • 5
    The first is syntactically correct C. The second is syntactically invalid in C (but is correct in C++ and means the same as the first when written in C++ code). – Jonathan Leffler Feb 02 '16 at 01:38
  • 2
    .... Though, in C++ you try to avoid those vanilla casts and instead would rather write: ``static_cast(int_var);`` – BitTickler Feb 02 '16 at 01:41

1 Answers1

2

As Jonathan Leffler stated, the first is from C and the second from C++:

The first one is a C-style cast; the second is the instantiation of a double by passing the constructor an int value.

So the second isn't really a cast but the creation of a new instance (So it is more C++ than C).

If you only do some C then using constructors isn't relevant (there is no Object Oriented Programming in C, that's a C++ feature).

If you're doing some C++ then you should avoid C-style casts (as @BitTickler stated) since problems can occure according the type of values you use it on. C++ provides several casts types for several cases.

See this answer for further informations.

Community
  • 1
  • 1
vmonteco
  • 14,136
  • 15
  • 55
  • 86