INT_MAX+1 = INT_MIN 是有符号整数吗? [英] Is INT_MAX+1 = INT_MIN in signed integer?
问题描述
for (i = 0; i <= N; ++i) { ... }
如果 N 是 INT_MAX
,则此特定语句将导致无限循环.知道无符号溢出正在包装溢出,假设 i
和 N
为无符号,编译器可以假设循环将精确迭代 N+1
次如果 i
在溢出时未定义.这里要注意的是:如果我将循环设为,
This particular statement will cause an infinite loop if N is INT_MAX
.
Having known that Unsigned Overflows are wrapping overflows, assuming i
and N
to unsigned, compiler can assume that the loop will iterate exactly N+1
times if i
is undefined on overflow.
The thing to note here is: if I make the loops as,
for (i = 0; i < N; ++i) { ... }
这仍然是未定义的行为吗?
Will this still be undefined behav?
在有符号整数的情况下,为什么 INT_MAX + 1
不一定等于 INT_MIN
?
Why INT_MAX + 1
is not surely equal to INT_MIN
in case of signed integers?
推荐答案
INT_MAX + 1
此操作调用未定义的行为.有符号整数溢出是 C 中未定义的行为.
this operation invokes undefined behavior. Signed integer overflow is undefined behavior in C.
它可能导致 INT_MIN
或者实现可以认为这个表达式是正的,否则程序会崩溃.不要让便携式程序计算这个表达式.
It can result to INT_MIN
or the implementation can consider this expression to be positive or the program can crash. Do not let a portable program compute this expression.
这篇关于INT_MAX+1 = INT_MIN 是有符号整数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!