coperatorsinteger-overflowsigned-integer

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


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?


Solution

  • 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.