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?
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.
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 / dis a double.The next thing that C++ does is add
ato the result ofb / 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 withc.In this example, division is handled first.
aandbare both ints, so no conversion is done. The result ofa / bis 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 / bis 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.