Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

299
Views
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

public class Java {
    public static void main(String[] args) {
        int i = 0;
        for (; i+1 > 0; i++) { }
        System.out.println(i);
    }
}
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!