-1

I tried comparing two INT_MAX and then comparing result of this with a integer and I'm getting this weird result.Could u please explain why this is happening?

#include <iostream>
#include <climits>
#include <bits/stdc++.h>
using namespace std;
  int main() {
    // your code goes here
    int a = 2;
    int option1 = min(INT_MAX, 1+INT_MAX);
    cout << "Result 1 " << option1 << endl;
    cout << "Result 2" << min(option1, 1+a);
    return 0;
}

It's giving this output:

Output:
    Result 1 -2147483648
    Result 2-2147483648

According to me result 2 should be 3 but it's giving something else.I'm not getting the reason behind this different output.

Deeksha
  • 35
  • 6

2 Answers2

3

This overflows

int option1 = min(INT_MAX, 1+INT_MAX);

The purpose of INT_MAX (or better: std::numeric_limits<int>::max()) is, well, to be a constant for the maximal int value that can be represented with the number of bytes that an int is on your system. If you add 1 to it, this is a signed integer overflow.

Signed integer overflows result in undefined behaviour. You can't really reason about the output of your program, as anything might happen. Note that as @Thomas and @largest_prime_is_463035818 pointed out in the comments, unsigned integer overflow isn't UB, it wraps around.

lubgr
  • 37,368
  • 3
  • 66
  • 117
1

INT_MAX is the largest positive value you can store in a (signed) int, when you add 1 to that you get undefined behavior. It's not that surprising, though, as (unsigned int) 0x7FFFFFFF + 1 == 0x80000000 which is the value -2147483648 in two's complement. Now you compare a large negative number with 3 and get the large negative value which would be as expected.

Allan Wind
  • 23,068
  • 5
  • 28
  • 38