Search code examples
cundefined-behaviorinteger-overflow

How can both (i + 1) < ii and (i + 1) > ii both be true?


I'm currently learning C program But I came across some weird behavior I expected one result but two results is printed like this

$ ./a.out
yes1 0x80000000
yes3 0x80000000

How could possible that?
I can't understand the result.

OS : x86_64 Ubuntu Linux
C compiler : gcc (Ubuntu/Linaro 4.8.1-10ubuntu9) 4.8.1

gcc -O2 weird.c

#include <stdio.h>

int main() {

    int i = 0x7fffffff;
    int ii = 0x0000000f;

    if ((i + 1) < ii)
        printf ("yes1 %#x\n", i + 1);

    if ((i + 1) == ii)
        printf ("yes2 %#x\n", i + 1);

    if ((i + 1) > ii)
        printf ("yes3 %#x\n", i + 1);

    return 0;
}

Solution

  • In your case (i+1) is overflowing over the range of the integer variable.

    The truth is that overflow on a signed int variable is an undefined behaviour in ANSI standard, so strictly speaking it may lead to any result. Your compiler may be conform to the standard but anyone with good computer understanding would expect that the variable will overflow to negative values simply because computer registers do not distinct signed/unsigned ranges.

    Here is what ANSI standard says on Undefined behavior (among other cases):

    The behavior in the following circumstances is undefined:

    An arithmetic operation is invalid (such as division or modulus by 0) or produces a result that cannot be represented in the space provided (such as overflow or underflow) ($3.3).

    On the other side, this is not valid for unsigned types:

    A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting unsigned integer type.

    Also here is the related part from referred section ($3.3 Expressions):

    If an exception occurs during the evaluation of an expression (that is, if the result is not mathematically defined or not representable), the behavior is undefined.