Why does -INT_MIN = INT_MIN in a signed, two's complement representation?

后端 未结 7 2129
一生所求
一生所求 2020-11-27 21:59

I still haven\'t found a reason why the lowest signed negative number doesn\'t have an equivalent signed positive number? I mean in a 3 digit binary number for simplicity 10

7条回答
  •  星月不相逢
    2020-11-27 22:19

    -INT_MIN is an integer overflow and is undefined behavior in C.

    -INT_MIN is guaranteed to be equal to INT_MIN only when signed integer overflows wrap. This can be enabled with gcc for example with -fwrapv option.

    Compiler usually take advantage of the fact that integer overflow is undefined behavior in C to perform some optimizations. Relying on signed integer overflows that wrap is unsafe.

    A well known example of compiler optimization is the following

    #define ABS(x) ((x) > 0 ? (x) : -(x)) 
    
    void foo(int x){  
        if (ABS(x) >= 0) {
            // some code
        }
    }
    

    most of the compilers today (gcc, icc) with the optimizations options enabled would optimize out the test relying on the fact that -INT_MIN is undefined behavior.

提交回复
热议问题