Does one double promote every int in the equation to double?

Alan Turing picture Alan Turing · Dec 1, 2012 · Viewed 50.3k times · Source

Does the presence of one floating-point data type (e.g. double) ensure that all +, -, *, /, %, etc math operations assume double operands?

If the story is more complicated than that, is there a resource that describes these rules? Should I not ask such questions and always explicitly cast int to double when the result of the equation is double. Here are some equations I'm thinking about. I purposefully did not compile and run then on my system, since this is the type of thing that could be compiler dependent.

int a(1), b(2), c(3);
double d(4.);
double result1 = a + b/d + c; // equal to 4 or to 4.5?
double result2 = (a + b)/d + c; // equal to 3 or to 3.75?    
double result3 = a/b + d; // equal to 4 or to 4.5?

Answer

Slix picture Slix · Dec 1, 2012

I purposefully did not compile and run then on my system, since this is the type of thing that could be compiler dependent.

This is not compiler dependent. C++ clearly defines the order of these operations and how they are converted.

How the conversion happens is dependent on the order of operations.

double result1 = a + b / d + c; // equal to 4 or to 4.5?

In this example, the division happens first. Because this is an int divided by a double, the compiler handles this by converting the int into a double. Thus, the result of b / d is a double.

The next thing that C++ does is add a to the result of b / d. This is an int added to a double, so it converts the int to a double and adds, resulting in a double. The same thing happens with c.

double result3 = a / b + d; // equal to 4 or to 4.5?

In this example, division is handled first. a and b are both ints, so no conversion is done. The result of a / b is of type int and is 0.

Then, the result of this is added to d. This is an int plus a double, so C++ converts the int to a double, and the result is a double.

Even though a double is present in this expression, a / b is evaluated first, and the double means nothing until execution reaches the double. Therefore, integer division occurs.

I find promotion and conversion rules pretty complex. Usually integer-like numbers (short, int, long) are promoted to floating-point equivalents (float, double). But things are complicated by size differences and sign.

See this question for specifics about conversion.