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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…