Operators that take two arithmetic operands in C always require both operands to be of the same type. If they aren't, then one or both are converted according to the usual arithmetic conversions, which are fully described in section 6.3.1.8 of the C standard (the link is to a draft of the 2011 standard).
Briefly:
- If either operand is of type
long double
, the other is converted tolong double
. - Otherwise, if either operand is of type
double
, the other is converted to `double. - Otherwise, if either operand is of type
float
, the other is converted tofloat
.
This is followed by a set of rules for two operands of integer type, which don't apply in this case.
If you need a double
result, you need to convert one or both operands to double
. If you convert just one of them, it will cause the other to be converted as well. (You might want to convert both just to be explicit.)
For example, if you have:
float f;
long n;
double x = f + n;
then the result of the addition is float
, which is converted to double
only after the addition is performed. To do a double
multiplication, change the last line to:
double x = (double)f + (double)n;
On the other hand, if you want a double
result, it's very likely that your float
operand should have been declared as a double
in the first place. double
is in some sense the "default" floating-point type in C (it's the type of unsuffixed literals like 1.0
, for example). float
is used mostly when it's important to save memory space, such as when you have very large arrays. On many systems, float
arithmetic isn't even any faster than double
arithmetic (though I'm not 100% sure on that last point).