How to portably find out min(INT_MAX, abs(INT_MIN))?

前端 未结 6 1364
感情败类
感情败类 2020-12-11 00:10

How can I portably find out the smallest of INT_MAX and abs(INT_MIN)? (That\'s the mathematical absolute value of INT_MIN, not a call

6条回答
  •  不思量自难忘°
    2020-12-11 00:14

    abs(INT_MIN) will invoke undefined behavior. Standard says

    7.22.6.1 The abs, labs and llabs functions:

    The abs, labs, and llabs functions compute the absolute value of an integer j. If the result cannot be represented, the behavior is undefined.

    Try this instead :
    Convert INT_MIN to unsignrd int. Since -ve numbers can't be represented as an unsigned int, INT_MAX will be converted to UINT_MAX + 1 + INT_MIN.

    #include 
    #include 
    
    unsigned min(unsigned a, unsigned b)
    {
        return a < b ? a : b;
    }
    
    int main(void)
    {
        printf("%u\n", min(INT_MAX, INT_MIN));
    }  
    

提交回复
热议问题