Search code examples
c++undefined-behaviorinteger-overflow

Is INT_MIN subtracted from any integer considered undefined behavior?


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?


Solution

  • 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.