整数溢出 - 为什么不呢 [英] Integer Overflow - Why not
问题描述
可能重复:
添加两个字符产生int
鉴于以下C ++代码:
Given the following C++ code:
unsigned char a = 200;
unsigned char b = 100;
unsigned char c = (a + b) / 2;
输出为逻辑预期的150,但是不应该有表达式中的整数溢出(a + b)
?
The output is 150 as logically expected, however shouldn't there be an integer overflow in the expression (a + b)
?
显然必须有一个整数提升才能处理这里溢出,或者其他一些我看不到的东西。我想知道是否有人可以启发我,所以我可以知道它是什么,不应该依赖于整数提升和溢出。
Obviously there must be an integer promotion to deal with the overflow here, or something else is happening that I cannot see. I was wondering if someone could enlighten me, so I can know what it is I can and shouldn't rely on in terms of integer promotion and overflow.
推荐答案
C ++和C都没有执行带有较小整数类型的算术计算,例如 char
和 short
。在进一步计算开始之前,这些类型几乎总是被提升为 int
。所以,你的表达式实际上被评估为
Neither C++ not C perform arithmetical computations withing "smaller" integer types like, char
and short
. These types almost always get promoted to int
before any further computations begin. So, your expression is really evaluated as
unsigned char c = ((int) a + (int) b) / 2;
P.S。在某些奇特的平台上, int
的范围不包括 unsigned char
的范围,类型 unsigned int
将用作促销的目标类型。
P.S. On some exotic platform where the range of int
does not cover the range of unsigned char
, the type unsigned int
will be used as target type for promotion.
这篇关于整数溢出 - 为什么不呢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!