有如下代码:
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, short
int, or unsigned short
int can be converted to an rvalue of type int if int can
represent all the values of the source type; otherwise, the source
rvalue 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 of
its underlying type:int, unsigned int,
long, orunsigned long.
3 An rvalue for an integral bit-field (9.6) can be converted
to an rvalue of typeintif intcan represent all
the values of the bit-field; otherwise, it can be converted
tounsigned intifunsigned intcan represent all the values of the
bit-field. If the bit-field is larger yet, no
integral promotion applies to it. If the
bit-field has an enumerated type, it is treated as any other
value of that type for promotion purposes.
4 An rvalue of typeboolcan be converted to an rvalue of
typeint, with falsebecoming zero andtrue
becoming one.
5 These conversions are calledintegral promotions.
翻译如下:
1. 类型 char, signed char, unsigned
char, short int, 或unsigned short int
会被转换为int类型如果int类型能表示上述类型的所有值;否则会被转换为unsigned int。
也就是说,a + b
其实直接提升为int类型了,结果不会为负数
本文通过一个具体的C++代码示例解释了当进行短整型变量相加操作时,为何不会出现预期的溢出错误。文章深入探讨了C++标准中关于整型提升的规则,并给出了详细的解释。
5241

被折叠的 条评论
为什么被折叠?



