Home > Software design >  Find biggest value in C using overflow and loop
Find biggest value in C using overflow and loop

Time:04-15

The task is to find the biggest int value with a loop. I have the exact same code almost in C and in Java. In Java it works fine, but in C I get the smallest value instead and I would like to know why.

C

#include <stdio.h>
int main() {
    int i = 0;
    for (; i 1 > 0; i  ) { }
    printf("%d", i);
    return 0;
}

Java

public class Java {
    public static void main(String[] args) {
        int i = 0;
        for (; i 1 > 0; i  ) { }
        System.out.println(i);
    }
}

CodePudding user response:

Your code seems to falsely assume that in C, an int is guaranteed to wrap to a negative number on overflow. This assumption is wrong. Such a signed integer overflow will invoke undefined behavior in C, so you cannot rely on any specific behavior if you let that happen.

In order to find the largest representable value of an int, you can use the macro constant INT_MAX, which is defined in limits.h.

Note however that it is only signed integer overflow that invokes undefined behavior in C. In constrast to that, when using unsigned numbers, they are guaranteed to wrap in a well-defined manner. Therefore, you could find the largest representable unsigned int using your method.

Also, some compilers have a setting that will cause the behavior of signed integer overflow to become well-defined (assuming that your hardware supports it and uses two's complement for representing signed numbers, which is probably the case). In gcc and clang, you can use the -fwrapv compiler command-line option to achieve this.

  • Related