pointers-memory · intermediate · ~15 min

Overflow-checked addition

Detect undefined-behaviour overflow before it happens.

Challenge

Implement int checked_add(int a, int b, int *out) returning 1 and storing a+b in *out when the sum fits in an int, or returning 0 (leaving *out unchanged) on signed overflow.

Starter code

#include <limits.h>

int checked_add(int a, int b, int *out) {
    /* TODO */
    return 0;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.