How to check for signed integer overflow in C without undefined behaviour?

后端 未结 3 1944
耶瑟儿~
耶瑟儿~ 2020-11-30 04:43

There\'s (1):

// assume x,y are non-negative
if(x > max - y) error;

And (2):

// assume x,y are non-negative
int sum = x          


        
3条回答
  •  悲&欢浪女
    2020-11-30 05:20

    You only have to check one of them. If x + y overflows, it will be less than both x and y. Hence:

    int sum = x + y;
    if (sum < x) error;
    

    should be sufficient.

    The following site has a bunch of stuff about integer overflow:

    http://www.fefe.de/intof.html

    If you want to handle negative numbers, it can be expanded:

    int sum = x + y;
    if (y >= 0) {
       if (sum < x) error;
    } else {
       if (sum > x) error;
    }
    

提交回复
热议问题