Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the product of 2147453647*2147453647 show 1 and -2147453648*-2147453648 shows 0 in the below C++ program?

Tags:

c++

int

range

I have declared two int variables: n1=2147483647 (the maximum value for my compiler), and n2=-2147453648 (the minimum value). The results of n1*n1 and n2*n2 are surprisingly 1 and 0.

Why these values? If it is related to the range of the data type, then could it not be any value, or the largest value an int can hold?

int main()
{
    int n1 = 2147483647;
    cout << "Product is : " << n1 * n1 << endl;

    int n2 = -2147483648;
    cout << "Product is : " << n2 * n2 << endl;

    return 0;
}

1 Answers

Signed integer overflow is undefined behaviour (reference).

Now, if you're wondering how these specific values arise in your particular environment, they're quite simply the 32 least-significant bits (LSB) of the result:

  • 2147483647*2147483647 equals 0x3fffffff00000001, the 32 LSB of which is 0x00000001;
  • -2147483648*-2147483648 equals 0x4000000000000000, the 32 LSB of which is 0x00000000.
like image 170
NPE Avatar answered Dec 02 '25 17:12

NPE