Home > other >  In C, why does "INT_MAX * INT_MAX" product gives 1?
In C, why does "INT_MAX * INT_MAX" product gives 1?

Time:01-11

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

CodePudding user response:

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

CodePudding user response:

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.

  •  Tags:  
  • Related