RussianPenguin
9/1/2018 - 12:31 PM

Вычитание с проверкой целочисленного переполнения

Выполняется целочисленное вычитание. При переполнении выдается исключение.

    int sub(int lhs, int rhs)
    {
        if(lhs < 0 && std::numeric_limits<int>::min() - lhs > -rhs) {
            throw std::runtime_error("signed underflow has occured");
        }
        return lhs - rhs;
    }