1

When I execute the following code:

cout<<min(INT_MAX, INT_MAX+ INT_MAX);

I obtain -2 as the output. Can someone explain why?
Shouldn't the output be the value of INT_MAX?

msc
  • 33,420
  • 29
  • 119
  • 214
Sh.A
  • 87
  • 1
  • 11
  • And what value did you expected to see? – Roman Podymov Sep 02 '17 at 09:14
  • What do you think the type and value of `INT_MAX+INT_MAX` should be? –  Sep 02 '17 at 09:15
  • BTW, `min` isn't (or at least shouldn't be) a macro. –  Sep 02 '17 at 09:16
  • 3
    Signed integer overflow is undefined behavior, so there is no guarantee for anything here. – nwp Sep 02 '17 at 09:16
  • @hvd [`min` is a macro in MSVC](https://stackoverflow.com/q/5004858/995714) – phuclv Sep 02 '17 at 09:21
  • 1
    @LưuVĩnhPhúc There's a reason I included the parenthesised bit :) –  Sep 02 '17 at 09:23
  • 1
    With a practical compiler and two's complement form you get wrap-around for the sum, and (2^n/2-1) + (2^n/2-1) ≈ -2 modulo 2^n. With a compiler (or options) that treat most any UB as a free license to do someting unexpected that two or three persons on the planet might regard as an optimization, anything can happen. That's about it. – Cheers and hth. - Alf Sep 02 '17 at 09:23
  • You're gonna need a bigger type https://ideone.com/79yTqx ... – Bob__ Sep 02 '17 at 09:40
  • To better see what's going on, simplify. `std::cout << (INT_MAX + INT_MAX) << 'in';` will show you what's happening. It has nothing to do with `min`. – Pete Becker Sep 02 '17 at 10:27

1 Answers1

5

INT_MAX+ INT_MAX invokes undefined behavior because signed integer overflow.

C++ 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.

msc
  • 33,420
  • 29
  • 119
  • 214
  • You can enable wrapping for signed integers in GCC using [`-fwrapv`](https://gcc.gnu.org/onlinedocs/gcc-7.2.0/gcc/Code-Gen-Options.html). – Henri Menke Sep 02 '17 at 11:17