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

423
Visualizações
Why does "INT_MAX * INT_MAX" product give 1?

I was learning computer architecture and decided to experiment with multiplication overflow. An overflow is observed for INT_MAX * INT_MAX, but I am not sure why this gives the product 1 in C/C++.

#include <stdio.h>
#include <limits.h>

int main()
{
    int num = INT_MAX;
    printf("%0x\n", num);       //stdout is 0x7fffffff
    printf("%d\n", num * num);  //stdout is 1
    return 0;
}
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Note: your code is invalid. Overflowing int * int is undefined behavior, and you should not write such code. The result will be unpredictable. This is a toy example where a compiler chooses to act in a specific way - but generally, the compiler is allowed to do anything with your code. If you want signed overflow to be defined, see for exmaple Is signed overflow still undefined behaviour in gcc when -fwrapv is used? .


For example, let's assume int on your platform has 32-bits and is twos-complement. The result is calculated, and then truncated to 32-bits.

INT_MAX = 0x7fffffff = 2147483647
2147483647 * 2147483647 = 4611686014132420609
4611686014132420609     = 0x3fffffff00000001
32-bits from 0x3fffffff00000001 = 0x00000001 = 1
over 4 years ago · Santiago Trujillo Relatório

0

In different machine, the size of data type "int" may be different. It may be 32 bits or 64 bits which depends on what machine you use. The typical ranges for "int" for 32 bit programs is from -2^31(minimum) to 2^31-1(maximum). The typical ranges for "int" for 64 bit programs is from -2^63(minimum) to 2^63-1(maximum).

If your program is 32 bits, the result is (2^31-1)(2^31-1) = 2^62-2^32+1. Since 2^62-2^32 will only be represented in the upper 32 bits of binary result, the overflow result you will get is 1. Otherwise, if your program is 64 bits, then (2^63-1)(2^63-1) = 2^126-2^64+1 will also lead to same result by truncating the upper 64 bits.

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