请检查以下代码片段:
unsigned char a = 100;
unsigned char b = 100;
unsigned char c = 100;
unsigned short x = a * b + c;
我预计这会溢出,计算将以 8 位类型的无符号字符(而不是 16 位无符号短字符(完成,超出无符号字符的值范围。但事实并非如此。
为什么计算在 C 和 C++ 中不会溢出?
[...]算术运算符不接受小于int的类型作为参数,如果适用,则在左值到右值转换后自动应用积分提升。
http://en.cppreference.com/w/cpp/language/implicit_conversion#Integral_promotion
所以你的代码是这样的:
unsigned char a = (unsigned char)100;
unsigned char b = (unsigned char)100;
unsigned char c = (unsigned char)100;
unsigned short x = (unsigned short)((int)a * (int)b + (int)c);