float + (short)long = ?
I am adding these types and based on my calculation I am getting a float as an answer but the right answer is double. can anyone give me an example of how it becomes double or explanation..
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:
long double
, the other is converted to long double
.double
, the other is converted to `double.float
, the other is converted to float
.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).