Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

floating-point promotion : stroustrup vs compiler - who is right?

Tags:

c++

c++11

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?

like image 567
kiba Avatar asked Jun 20 '13 13:06

kiba


1 Answers

I don't know what exactly Stroustrup's book says, but according to the standard, floats will not be converted to doubles 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 shorts to be converted to ints. But two floats will not be converted to doubles 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.

like image 53
interjay Avatar answered Oct 05 '22 19:10

interjay