Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

303
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda