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

本文通过一个具体的C++代码示例解释了当进行短整型变量相加操作时,为何不会出现预期的溢出错误。文章深入探讨了C++标准中关于整型提升的规则,并给出了详细的解释。
有如下代码:
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类型了,结果不会为负数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值