Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find biggest value in C using overflow and loop

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

Your code seems to falsely assume that in C, an int is guaranteed to wrap to a negative number on overflow. This is not necessarily the case. 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading