0

If I have an expression like the following:

double d = floatVar / intVar;

intVar will be promoted to a float and then the returned float result will be converted to a double and assigned to d. But what happens if I have a long expression, such as:

double d = floatVar / intVar * shortVar + charVar + intVar2;

Will all of the variables be promoted to a float, and then the returned float result will be converted to a double and assigned to d?

Also if I have the following:

double d = (floatVar / intVar) * shortVar + charVar + intVar2;

Will intVar be converted to a float, while shortVar and charVar will be converted to an int, and then the returned int result from shortVar + charVar + intVar2 will be converted to a float and multiplied with the returned float result of (floatVar / intVar), and this returned float result will be converted to a double and assigned to d?

John
  • 1,049
  • 1
  • 14
  • 34

1 Answers1

2

Order of operations applies. / and * and + are all left-associative, and / and * have equal precedence (which is greater than that of +), so this:

double b = floatVar / intVar * shortVar + charVar + intVar2;

is equivalent to this:

double b = (((floatVar / intVar) * shortVar) + charVar) + intVar2;

At each step, the appropriate conversions are performed: intVar is converted to float, shortVar is converted to float, charVar is converted to float, intVar2 is converted to float. The end-result is promoted to double.

If, on the other hand, you were to wrap charVar + intVar2 in parentheses to force that operation to take place first, then charVar would be promoted to int (assuming that the range of char fits within the range of int, as it does on almost any system you're likely to encounter), and the resulting sum would be converted to float.

ruakh
  • 175,680
  • 26
  • 273
  • 307
  • "assuming that char is a signed type" What if `char` is an unsigned type, what will happen here: `(charVar + intVar2)`? – John Jan 22 '15 at 07:14
  • @John: Usually the same, actually. The only case where something different happens is if `char` is an unsigned type *and* its range does not fit in the range of `int`. (`int` is required to support at least the range of a sixteen-bit one's-complement value, and `char` is required to be the size of a byte, so I think this is only possible on a system where bytes have 16 or more bits. So, vanishingly rare. I'll adjust my answer to avoid implying that it's more common than it is.) – ruakh Jan 22 '15 at 07:27