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);
}
}
>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.