当一个整数溢出在C前pression时会发生什么? [英] What happens when a integer overflow occurs in a C expression?
问题描述
我有以下的C code:
I have the following C code:
uint8_t firstValue = 111;
uint8_t secondValue = 145;
uint16_t temp = firstValue + secondValue;
if (temp > 0xFF) {
return true;
}
return false;
这是另类实现:
uint8_t firstValue = 111;
uint8_t secondValue = 145;
if (firstValue + secondValue > 0xFF) {
return true;
}
return false;
第一个例子是显而易见的, uint16_t
类型是大到足以容纳结果。
当我试图用铛
在OS编译器的第二个例子/ X,它正确返回真。那里发生什么?是否有某种的临时的,更大的类型包含结果?
The first example is obvious, the uint16_t
type is big enough to contain the result.
When I tried the second example with the clang
compiler on OS/X, it correctly returned true. What happens there? Is there some sort of temporary, bigger type to contain the result?
推荐答案
+
的操作数提升到更大的类型,我们可以去看到这个的草案C99标准部分 6.5.6
的加法运算符的它说:
The operands of +
are promoted to larger types, we can see this by going to draft C99 standard section 6.5.6
Additive operators which says:
如果两个操作数的算术类型,通常的算术转换执行上
它们。
If both operands have arithmetic type, the usual arithmetic conversions are performed on them.
如果我们去 6.3.1.8
的常见的算术转换的它说:
另外,整数促销活动是在两个操作数执行。
Otherwise, the integer promotions are performed on both operands.
然后我们去 6.3.1.1
的布尔,字符和整数的它说(的重点煤矿的)
and then we go to 6.3.1.1
Boolean, characters, and integers which says (emphasis mine):
如果int可以重新present原始类型的所有值,该值被转换为int;
否则,将其转换为一个unsigned int。 这些被称为整数
促销活动 0.48),而所有其它类型的整数提升不会改变。
If an int can represent all values of the original type, the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions.48) All other types are unchanged by the integer promotions.
所以 +
在这种情况下,两个操作数将晋升为键入的 INT 的的操作,所以没有溢出。
So both operands of +
in this case will be promoted to type int for the operation, so there is no overflow.
请注意,为什么一定要短在C转换为int算术运算之前和C ++?说明理由促销活动。
Note, Why must a short be converted to an int before arithmetic operations in C and C++? explains the rationale for promotions.
这篇关于当一个整数溢出在C前pression时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!