我有以下C代码:
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上使用clang编译器尝试第二个示例时,它正确地返回true。 那里会发生什么? 是否有某种临时的 ,更大的类型来包含结果?
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;This is the alternative implementation:
uint8_t firstValue = 111; uint8_t secondValue = 145; if (firstValue + secondValue > 0xFF) { return true; } return false;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来看到这一点。 添加操作符说:
如果两个操作数都具有算术类型,则通常会对它们执行算术转换。
如果我们转到6.3.1.8 通常的算术转换,它会说:
否则,整数升级在两个操作数上执行。
然后我们转到6.3.1.1 布尔,字符和整数 ,它们表示( 强调我的 ):
如果int可以表示原始类型的所有值,则该值将转换为int; 否则,它被转换为一个unsigned int。 这些被称为整数促销 .48)所有其他类型均不受整数促销的影响。
因此,在这种情况下+两个操作数将被提升为操作的int类型,所以没有溢出。
注意, 在C和C ++的算术运算之前 , 为什么必须将一个短整数转换为整数? 解释促销的理由。
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.
and if we go to 6.3.1.8 Usual arithmetic conversions it says:
Otherwise, the integer promotions are performed on both operands.
and then we go to 6.3.1.1 Boolean, characters, and integers which says (emphasis mine):
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.
So both operands of + in this case will be promoted to type int for the operation, so there is no overflow.
Note, Why must a short be converted to an int before arithmetic operations in C and C++? explains the rationale for promotions.
更多推荐
发布评论