1

gcc version:gcc (GCC) 8.4.1 20200928 (Red Hat 8.4.1-1)

glibc version:glibc 2.28

#include <stdio.h>

int main (void)
{
  int i = 2147000003;
  int iplus = i+1000000; //-2146967293

  printf ("i is %d\n", i);//2147000003
  printf ("iplus is %d\n", iplus);//-2146967293
  printf ("i+1000000 is %d\n", i+1000000);//-2146967293

  printf ("iplus %s i\n", iplus < i ? "less than" : "not less than"); //less than
  printf ("i+1000000 %s i\n", (i+1000000) < i ? "less than" : "not less than");//not less than

  return 0;
}

execute:

i is 2147000003
iplus is -2146967293
i+1000000 is -2146967293
iplus less than i
i+1000000 not less than i

I think the variable iplus is the same as i+1000000, but it's not. Why?

I think i+1000000 less than i but i+1000000 not less than i.


See the comment area for the answer.

Just like the comments, the correct answer should be "the compiler optimizes the logic of i+a positive number<i to be constant false", because this is not true in mathematics. This question is not a duplicate question. This question does not explore the overflow problem, but a compiler optimization problem.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
tyroc
  • 55
  • 5
  • 4
    Signed integer overflow is undefined. – wildplasser Jun 21 '21 at 10:32
  • 1
    `2147000003 + 1000000` isn't `-2146967293`. When you have (signed) integer overflow the behavior is undefined. The result of comparing something resulting from signed overflow with another value can generate any result. – Support Ukraine Jun 21 '21 at 10:37
  • 5
    In ordinary math, `(i+1000000) < i` is always false. Since it is always false, it is a simplification and a program optimization to replace the expression by “false.” Since the behavior on overflow is undefined, the compiler is allowed to make this simplification without any concern about how it affects the rest of the program. In contrast, in `int iplus = i+1000000;`, there is no similar simplification. The “easiest” thing for the compiler to do is simply to perform the addition, which wraps when implemented with a machine instruction. This is allowed regardless of how it affects the program. – Eric Postpischil Jun 21 '21 at 10:44

0 Answers0