问题
for (i = 0; i <= N; ++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?
Why INT_MAX + 1
is not surely equal to INT_MIN
in case of signed integers?
回答1:
INT_MAX + 1
this operation invokes undefined behavior. Signed integer overflow is undefined behavior in C.
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.
回答2:
Why INT_MAX + 1 is not surely equal to INT_MIN in case of signed integers?
First, the behaviour on integer overflow is undefined by the C standard. Most implementations seem to let the number just overflow silently, so let's assume that is the case.
Second, the C standard does not assume twos's complement integers. Most platforms use it, especially newer ones. There are (were) older platforms that use other integer representations, for instance one's complement. Overflow in one's complement results in negative zero.
Relying on undefined behaviour to work in any particular way is really bad programming practice as it makes the program so much less portable. Even OS or compiler upgrades may change undefined behaviour, so it might not even be portable between different versions of the same OS.
来源:https://stackoverflow.com/questions/19376682/is-int-max1-int-min-in-signed-integer