Question

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?

Was it helpful?

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.

OTHER TIPS

This is signed integer overflow and thus undefined behavior, this Cert document on how to Ensure that operations on signed integers do not result in overflow is great and as far as I can tell covers all the instances. This is the if statement from the Division section that covers your question:

if ( (sl2 == 0) || ( (sl1 == LONG_MIN) && (sl2 == -1) ) ) {
  /* Handle error condition */
}
else {
  result = sl1 / sl2;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top