3

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;
}
Boann
  • 48,794
  • 16
  • 117
  • 146

1 Answers1

4

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.
NPE
  • 486,780
  • 108
  • 951
  • 1,012