<分区>
请检查以下代码段:
unsigned char a = 100;
unsigned char b = 100;
unsigned char c = 100;
unsigned short x = a * b + c;
我预计这会溢出并且计算将在 8 位类型的 unsigned char 中完成(而不是在 16 位 unsigned short 中),超出 unsigned char 的取值范围。但事实并非如此。
为什么在C和C++中计算不会溢出?
标签 c++ c integer-overflow
<分区>
请检查以下代码段:
unsigned char a = 100;
unsigned char b = 100;
unsigned char c = 100;
unsigned short x = a * b + c;
我预计这会溢出并且计算将在 8 位类型的 unsigned char 中完成(而不是在 16 位 unsigned short 中),超出 unsigned char 的取值范围。但事实并非如此。
为什么在C和C++中计算不会溢出?
最佳答案
[...] arithmetic operators do not accept types smaller than int as arguments, and integral promotions are automatically applied after lvalue-to-rvalue conversion, if applicable.
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);
关于c++ - C和C++中整数计算的溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49252193/