In section 10.5.1 of Stroustrup's new book "The C++ Programming Language - Fourth Edition" he says, that before an arithmetic operation is performed, integral promotion is used to create ints out of shorter integer types, and similarly, floating-point promotion is used to create doubles out of floats.
I confirmed the first claim with the following code:
#include <iostream> #include <typeinfo> int main() { short a; short b; std::cout << typeid(a + b).name() << std::endl; }
This outputs "int" with vc++ and "i" with gcc.
But testing it with floats instead of shorts, the output is still "float" or "f":
#include <iostream> #include <typeinfo> int main() { float a; float b; std::cout << typeid(a + b).name() << std::endl; }
According to Stroustrup there are no exceptions to the floating-point promotion-rule, so I expected "double" or "d" as output.
Is the mentioned section about promotions wrong or somehow unclear? And is there any difference in C++98 and C++11 regarding type promotions?
I don't know what exactly Stroustrup's book says, but according to the standard, float
s will not be converted to double
s in this case. Before applying most arithmetic binary operators, the usual arithmetic conversions described in 5p9 are applied:
- If either operand is of scoped enumeration type (7.2), no conversions are performed; if the other operand does not have the same type, the expression is ill-formed.
- If either operand is of type long double, the other shall be converted to long double.
- Otherwise, if either operand is double, the other shall be converted to double.
- Otherwise, if either operand is float, the other shall be converted to float.
- Otherwise, the integral promotions (4.5) shall be performed on both operands. [...]
The integral promotions are what causes two short
s to be converted to int
s. But two float
s will not be converted to double
s according to these rules. If you add a float
to a double
, the float
will be converted to a double
.
The above is from C++11. C++03 contains the same rules, except for the one referring to scoped enumerations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With