2

This program is asking the C implementation to answer a simple question:

If we check the largest re-presentable integer INT_MAX < 0 and print it.

printf ("%d\n", (INT_MAX) < 0);

So, displayed output 0. because condition become false and relational operator return 0.

But, If we add 1 to the largest re-presentable integer and check condition, See following program.

#include <limits.h>
#include <stdio.h>

int main (void)
{
  printf ("%d\n", (INT_MAX+1) < 0);
  return 0;
}

and displayed output 1.

Why condition not become false?

Also, if we add one to the largest re-presentable integer, is the result negative?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
msc
  • 33,420
  • 29
  • 119
  • 214

4 Answers4

7

If we add one to the largest re-presentable integer, is the result negative?

No. Signed integer overflow is undefined behaviour. You may observe as if it wraps around in 2's complement representation. But that's just implementation specific behaviour and the C standard makes absolutely no such guarantee anything.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
P.P
  • 117,907
  • 20
  • 175
  • 238
5

INT_MAX being a signed value, INT_MAX + 1 is causing a signed integer overflow, which invokes undefined behavior.

The output (if at all) of a(ny) program containing UB cannot be justified in any way.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
5

The behaviour of INT_MAX + 1 is undefined as you will be overflowing a signed type.

The program could output anything, or the compiler could eat your cat.

(Out of interest, this is why you'll see -INT_MAX - 1 as the definition of INT_MIN on a 2's complement system.)

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
-1
INT_MAX = 0x7fffffff
INT_MAX + 1 = 0x80000000 = -2147483648 < 0
Wiki Wang
  • 668
  • 6
  • 23