#include <iostream>
#include <typeinfo>
using namespace std;
int main()
{
int s = 2;
unsigned int u = 3;
auto k = s + u;
if (typeid(k) == typeid(s))
cout << "signed" << endl;
else if (typeid(k) == typeid(u))
cout << "unsigned" << endl;
else
cout << "error" << endl;
}
GCC 该程序的输出是:
unsigned
我很确定这要么是未定义的行为,要么是实现定义的行为 - 但我似乎无法将这些点与标准联系起来。
你能告诉我标准中哪里有这样的说法吗?
你看到的只是效果常用算术转换 http://channel9.msdn.com/Series/C9-Lectures-Stephan-T-Lavavej-Core-C-/Stephan-T-Lavavej-Core-C-7-of-n.
该标准规定如下:
§5 [expr] p7
:
许多需要算术或枚举类型操作数的二元运算符会以类似的方式导致转换并产生结果类型。目的是产生一个通用类型,这也是结果的类型。这种模式称为通常的算术转换,其定义如下:
- [...]
- Otherwise, the integral promotions (4.5) shall be performed on both operands. Then the following rules shall be applied to the promoted operands:
- [...]
- 否则,两个操作数都应转换为与有符号整数类型操作数的类型相对应的无符号整数类型。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)