LOGBOOK

HELP

Quiz Entry - updated: 2026.07.07

How do you safely check for signed integer overflow before it happens?

Test the operands against INT_MAX/INT_MIN before the operation (or use a compiler builtin) — you can't reliably detect signed overflow afterwards, since it's undefined behavior.

// Addition overflow check
bool will_overflow_add(int a, int b) {
    if (b > 0 && a > INT_MAX - b) return true;
    if (b < 0 && a < INT_MIN - b) return true;
    return false;
}

// Multiplication overflow check
bool will_overflow_mul(int a, int b) {
    if (a > 0 && b > 0 && a > INT_MAX / b) return true;
    if (a > 0 && b < 0 && b < INT_MIN / a) return true;
    if (a < 0 && b > 0 && a < INT_MIN / b) return true;
    if (a < 0 && b < 0 && a < INT_MAX / b) return true;
    return false;
}

Alternative: Use compiler built-ins like __builtin_add_overflow() in GCC/Clang.

From Quiz: REVE1 / Number Representations | Updated: Jul 07, 2026