Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is INT_MAX + (-1) an undefined behavior?

In C++ an overflow of signed types is undefined behavior. Is the following example an undefined behavior as well?

#include <limits.h>

int f() {
  int a = INT_MAX;
  int b = -1;
  return a + b;
}

It is not an overflow in math context, but a CPU will see it probably like add 0x7fffffff 0xffffffff.

like image 916
Paweł Bylica Avatar asked Nov 30 '22 14:11

Paweł Bylica


1 Answers

The example you give is not an overflow.

From Wikipedia (https://en.wikipedia.org/wiki/Integer_overflow):

... an integer overflow occurs when an arithmetic operation attempts to create a numeric value that is outside of the range that can be represented with a given number of bits – either larger than the maximum or lower than the minimum representable value.

INT_MAX + (-1) is not outside of the range representable by the int type, and the result is defined.

like image 161
payne Avatar answered Dec 09 '22 14:12

payne