浮点升级:stroustrup与编译器-谁是对的? [英] floating-point promotion : stroustrup vs compiler - who is right?
问题描述
在Stroustrup的新书 C ++编程语言-第四版的第10.5.1节中,他说,在执行算术运算之前,使用整数提升从较短的整数类型中创建整数,并且类似地,点奖励用于创建浮点数的双打。
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;
}
此命令会在vc ++中输出 int,在gcc中输出 i。
This outputs "int" with vc++ and "i" with gcc.
但是用浮子而不是短裤进行测试,输出仍然是 float或 f:
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;
}
根据Stroustrup,浮点促销规则没有例外,所以我期望输出为 double或 d。
According to Stroustrup there are no exceptions to the floating-point promotion-rule, so I expected "double" or "d" as output.
上述提到的有关促销的部分是错误的还是不清楚? C ++ 98和C ++ 11在类型提升方面有什么区别吗?
Is the mentioned section about promotions wrong or somehow unclear? And is there any difference in C++98 and C++11 regarding type promotions?
推荐答案
我不知道什么正是Stroustrup的书说的那样,但是根据标准,在这种情况下,浮动
s不会转换为 double
s。在应用大多数算术二进制运算符之前,将应用5p9中描述的常规算术转换:
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:
- 如果任何一个操作数都属于范围枚举类型(7.2),则不执行任何转换;如果另一个操作数的类型不同,则表达式格式错误。
- 如果其中一个操作数为long double类型,则另一个应转换为long double。
- 否则,如果其中一个操作数为double,则另一个
- 否则,如果其中一个操作数为float,则另一个操作数应转换为float。
- 否则,积分提升( 4.5)应在两个操作数上执行。 [...]
- 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. [...]
积分促销是造成两个短缺的原因
转换为 int
s。但是,根据这些规则,两个 float
不会转换为 double
s。如果将 float
添加到 double
,则 float
将会被转换为 double
。
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
.
上面的内容来自C ++ 11。 C ++ 03包含相同的规则,只是其中一个引用了范围枚举。
The above is from C++11. C++03 contains the same rules, except for the one referring to scoped enumerations.
这篇关于浮点升级:stroustrup与编译器-谁是对的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!