Integer division overflows

后端 未结 2 1702
慢半拍i
慢半拍i 2020-12-31 08:55

The Problem

I have been thinking about integer (type int) overflows, and it occurs to me that division could overflow.

Example: On my curr

2条回答
  •  遥遥无期
    2020-12-31 09:19

    What guarantees (in C or C++ standard) might help to devise the code?

    C specifies signed integer representation as using 1 of 3 forms: sign and magnitude, two’s complement, or ones’ complement. Given these forms, only division by 0 and two’s complement division of INT_MIN/-1 may overflow.

    What (cross-platform) C code could one write in order to prevent division overflows (for type (signed) int)?

    int safe_int_div(int * res, int op1, int op2) {
      if (op2 == 0) {
        return 1;
      }
      // 2's complement detection
      #if (INT_MIN != -INT_MAX) 
        if (op1 == INT_MIN && op2 == -1)  {
          return 1;
        }
      #endif
      *res = op1 / op2;
      return 0;
    }
    

提交回复
热议问题