[原创]c++整型提升(类型转换)

来源:互联网 发布:cocos2dx 游戏源码 编辑:程序博客网 时间:2024/06/06 09:32
有如下代码:
signed short a = 1;
signed short b = 0x7fff;
signed short c = 0;
if ( (a + b) < c )
{
cout <<"over flow"<<endl;
}
else
{
cout <<"no error"<<endl;
}
你觉得结果会是什么呢?
刚开始我感觉 a + b结果应该是 signed short,那么就应该是-1,结果应该是溢出的。
而实际运行却是输出no error。
坑爹。原因如下:

以下摘自C++ standard 2003:
1 An rvalue of type char, signed char, unsigned char, shortint, or unsigned short
int can be converted to an rvalue of type int if int canrepresent all the values of the source type; otherwise, the sourcervalue can be converted to an rvalue of type unsigned int.
2 An rvalue of typewchar_t(3.9.1) or an enumeration type (7.2)can be converted to an rvalue of the first
of the following types that can represent all the values ofits underlying type:int, unsigned int,
long, orunsigned long.
3 An rvalue for an integral bit-field (9.6) can be convertedto an rvalue of typeintif intcan represent all
the values of the bit-field; otherwise, it can be convertedtounsigned intifunsigned intcan represent all the values of thebit-field.  If the bit-field is larger yet, nointegral promotion applies to it.  If the
bit-field has an enumerated type, it is treated as any othervalue of that type for promotion purposes.
4 An rvalue of typeboolcan be converted to an rvalue oftypeint, with falsebecoming zero andtrue
becoming one.
5 These conversions are calledintegral promotions.

翻译如下:
1. 类型 char, signed char, unsignedchar, short int, 或unsigned short int会被转换为int类型如果int类型能表示上述类型的所有值;否则会被转换为unsigned int。

也就是说,a + b其实直接提升为int类型了,结果不会为负数

0 0
原创粉丝点击