问题
What if I have something like this:
int a = 20;
int min = INT_MIN;
if(-a - min)
//do something
Assume that INT_MIN if positive is more than INT_MAX. Would min ever be converted by the compiler to something like -min as in -INT_MIN, which could be undefined?
回答1:
You are right that unary minus applied to INT_MIN
can be undefined, but this does not happen in your example.
-a - min
is parsed as (-a) - min
. Variable min
is only involved in binary subtraction, and the first operand only needs to be strictly negative for the result to be defined.
If the compiler transforms the subtraction to something else, it is its responsibility to ensure that the new version always computes the same thing as the old version.
回答2:
The result of x - y
is defined as the mathematical result of subtracting y
from x
. If the mathematical result can be represented in the result type (int
in this case), then there is no overflow.
A compiler is free to transform the expression in any way it likes, such as by changing
x - y
to
x + (-y)
but only if the transformation keeps the same behavior in cases where the original behavior is well defined. In the case of y == INT_MIN
, it can still perform the transformation as long as the undefined behavior of evaluating -INT_MIN
yields the same end result (which it typically will).
To answer the question in the title:
Is INT_MIN subtracted from any integer considered undefined behavior?
INT_MIN - INT_MIN == 0
, and cannot overflow.
Incidentally, I think you mean int
rather than "integer". int
is just one of several integer types.
来源:https://stackoverflow.com/questions/19015444/is-int-min-subtracted-from-any-integer-considered-undefined-behavior