How to check if integer multiplication will overflow in C++

1 Answer

0 votes
#include <iostream>
#include <cstdint>

bool multiplyWillOverflow(uint64_t x, uint64_t y) {
    if (x <= 1 || y <= 1) {
        return false;
    }

    uint64_t d = x * y;
    
    return d / y != x;
}

int main() {
    uint64_t x = 3, y = 1472783642;
    std::cout << (multiplyWillOverflow(x, y) ? "true" : "false") << std::endl;

    x = 9223372036854775807;
    y = 5;
    std::cout << (multiplyWillOverflow(x, y) ? "true" : "false") << std::endl;
}



/*
run:

false
true

*/

 



answered May 18, 2025 by avibootz
...