[原创]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
- [原创]c++整型提升(类型转换)
- C语言 sizeof 整型提升 类型转换
- C语言中的数值类型转换:整型提升/寻常算术变化/截断/强制类型转换
- 隐式类型转换和整型提升
- c 整型提升和算数转换
- C进阶指南(1):整型溢出和类型提升、内存申请和管理
- C进阶指南(1):整型溢出和类型提升、内存申请和管理
- C进阶指南(1):整型溢出和类型提升、内存申请和管理
- C进阶指南(1):整型溢出和类型提升、内存申请和管理(转)
- C中的整型提升
- C中的整型提升
- C专家编程-整型提升与寻常算术转换
- char 类型的整型提升
- 【C语言】整型溢出和整型提升
- C 语言中的整型提升
- C语言进阶:整型提升
- C语言进阶:整型提升
- C中字符类型和整型的转换
- 如何正确地在MDK中使用关键…
- [原创]计算ip首部检验和
- 胜者树与败者树的区别,外部排序
- java 读写绝对路径的properties文件
- c++编译器和连接器介绍
- [原创]c++整型提升(类型转换)
- linux下搭建基于Eclipse的ar…
- [原创]解决zlib.h:no such&nb…
- 从 Qt 的 delete 说开来
- [原创]解决使用Qt creator时…
- 多重背包O(N*V)算法详解(使…
- [原创]poj 1742 多重背包 单调队列
- 求无向连通图的最小生成树算…
- Linux权限位