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?
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?
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.