pointers-memory · intermediate · ~15 min

Overflow-checked addition

Detect undefined-behaviour overflow before it happens.

Challenge

Add two ints safely by detecting signed overflow before it happens (since signed overflow is undefined behaviour in C, you must test for it rather than perform the add and inspect the result).

Task

Implement int checked_add(int a, int b, int *out) that, when a + b fits in an int, stores the sum in *out and returns 1; on overflow it returns 0 and leaves *out unchanged. No main — the grader calls it.

Input

a, b — the operands. out — where to store the sum on success.

Output

Returns 1 with *out = a + b when the sum fits; returns 0 and leaves *out untouched on overflow/underflow.

Example

checked_add(2, 3, &o)         ->   1, o == 5
checked_add(INT_MAX, 1, &o)   ->   0, o unchanged
checked_add(INT_MIN, -1, &o)  ->   0, o unchanged

Edge cases

  • Positive overflow (a + b > INT_MAX): return 0.
  • Negative overflow (a + b < INT_MIN): return 0.

Rules

  • Detect overflow using comparisons against INT_MAX/INT_MIN; do not compute a + b and check afterwards.

Input format

a, b — operands; out — destination for the sum on success.

Output format

1 with *out = a + b on success; 0 (out unchanged) on overflow.

Constraints

Detect overflow before adding (signed overflow is UB); don't compute then check.

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.