Search code examples
c++mathinteger-overflowinteger-division

Is INT_MIN/-1 defined behavior in C++?


I have the following code for INT_MIN/-1. I would expect for this to have came out to be INT_MAX+1 (or 0 with rollover). However, the actual result I get is INT_MIN. This is my test code:

#define __STDC_LIMIT_MACROS
#include <stdint.h>
#include <stdio.h>
#include <limits.h>
using namespace std;
int main()
{
  int min=INT_MIN;
  int res=min/-1;
  printf("result: %i\n", res);
  printf("max: %i min: %i\n", INT_MAX, INT_MIN);
  return 0;
}

Is this implementation specific and/or undefined behavior?


Solution

  • Is this implementation specific and/or undefined behavior?

    Yes, signed integer overflow is undefined behavior. Per paragraph 5/4 of the C++11 Standard:

    If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined. [...]

    Notice, that the same does not apply to unsigned arithmetic. As specified in paragraph 3.9.1/4 and footnote 46:

    Unsigned integers, declared unsigned, shall obey the laws of arithmetic modulo 2^n where n is the number of bits in the value representation of that particular size of integer. [...]

    This implies that unsigned arithmetic does not overflow because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting unsigned integer type.