Ç整数溢出 [英] C integer overflow
问题描述
我在C整数工作,努力探索更多的溢出是如何发生的时候再打开。
I was working with integers in C, trying to explore more on when and how overflow happens.
我注意到,当我加了两个正数,其中溢出的总和,我总是得到一个负数。
I noticed that when I added two positive numbers, the sum of which overflows, I always got a negative number.
在另一方面,如果我添加了两个负数,其中溢出的总和,我总是有一个正数(包括0)。
On the other hand, if I added two negative numbers, the sum of which overflows, I always got a positive number (including 0).
我做了几个实验,但我想知道这是不是真的对每一个案件。
I made few experiments, but I would like to know if this is true for every case.
推荐答案
整数溢出在C未定义的行为。
Integer overflows are undefined behavior in C.
ç说,一名前pression涉及整数溢的,如果通常的算术转换后的结果是结果的类型psented签署的类型,不能再$ P $的。转让和投前pressions是个例外,因为它们是由整数转换裁定。
C says an expression involving integers overflows, if its result after the usual arithmetic conversions is of a signed typed and cannot be represented in the type of the result. Assignment and cast expressions are an exception as they are ruled by the integer conversions.
防爆pressions不能溢出,它们包住,即。克, 0U - 1
是 UINT_MAX
Expressions of unsigned type cannot overflow, they wrap, e. g., 0U - 1
is UINT_MAX
.
例如:
INT_MAX + 1 // integer overflow
UINT_MAX + 1 // no overflow, the resulting type is unsigned
(unsigned char) INT_MAX // no overflow, integer conversion occurs
不要让任何整数EX pression overlflows,现代的编译器(如 GCC
)充分利用整数溢出是执行各种类型的优化未定义的行为。
Never let any integer expression overlflows, modern compilers (like gcc
) take advantage of integer overflows being undefined behavior to perform various types of optimizations.
例如:
a - 10 < 20
在 A
的类型为 INT
升级后,前pression在<$ C降低$ C> GCC (优化在启用时)为:
when a
is of type int
after promotion, the expression is reduced in gcc
(when optimization are enabled) to:
a < 30
它采用前pression的优势是不确定的行为,当 A
的范围为 INT_MIN + 10 - 1
到 INT_MIN
。
该优化无法完成时 A
是 unsigned int类型
,因为如果 A
是 0
,那么 A - 10
已被评估为 UINT_MAX - 9
(无未定义行为)。优化 A - 10 LT; 20
到 A&LT; 30
然后会导致不同的结果比要求之一,当 A
是 0
来 9
。
This optimization could not be done when a
is unsigned int
because if a
is 0
, then a - 10
has to be evaluated as UINT_MAX - 9
(no undefined behavior). Optimizing a - 10 < 20
to a < 30
would then lead to a different result than the required one when a
is 0
to 9
.
这篇关于Ç整数溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!