0

Firstly, I defined two bit integers, and multiply them. The answer must overflow, and I got a negative number. Then, I defined two 64-bit integers, and multiply them. The answer must overflow, and I expected to get a negative number. But, the result was zero. I don't know why this happen, could anybody give me some help?

The code is below.

#include <iostream>

int main ()  
{
    
    int x = 1e9, y = 1e9;

    printf("%d\n", x * y);

    int64_t a = 36028797018963968;
    int64_t b = 36028797018963968;

    printf("%ld\n", a * b);
    
    return 0;
}

The result is below.

ubuntu@VM-0-2-ubuntu:~/Projects/Test$ g++ test.cpp -o a
ubuntu@VM-0-2-ubuntu:~/Projects/Test$ ./a
-1486618624
0
hojztuh
  • 13
  • 2
  • 2
    The results of signed integer overflow are undefined by C++. Your expectation of a negative number is incorrect. Unsigned integer overflow does have defined behaviour however. – john Nov 29 '22 at 07:32
  • [Why is unsigned integer overflow defined behavior but signed integer overflow isn't?](https://stackoverflow.com/questions/18195715/why-is-unsigned-integer-overflow-defined-behavior-but-signed-integer-overflow-is) and [Is signed integer overflow still undefined behavior in C++?](https://stackoverflow.com/questions/16188263/is-signed-integer-overflow-still-undefined-behavior-in-c), [Why is the phrase: "undefined behavior means the compiler can do anything it wants" true?](https://stackoverflow.com/questions/49032551/why-is-the-phrase-undefined-behavior-means-the-compiler-can-do-anything-it-wan) – Jason Nov 29 '22 at 07:33
  • Hi, thank you for your correction. I changed `int64_t` to `uint64_t`, and multiplied the two big numbers. I still got zero. It there a reasonable explanation? – hojztuh Nov 29 '22 at 07:55
  • @hojztuh 36028797018963968 is 2^55 or `10000000000000000000000000000000000000000000000000000000` in binary. If you multiply that with itself, then yes; you are going to get 0's in all the 64 low bits. – Frodyne Nov 29 '22 at 08:07

0 Answers0