pointers-memory · intermediate · ~14 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.

Why this matters

Drill: practice one contract before combining it with other skills.

Input format

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

Output format

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

Constraints

out points to a live writable int and is never NULL. Return 1 and store the sum when representable, else return 0 leaving *out unchanged. Do not perform signed overflow.

Starter code

#include <limits.h>

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

Common mistakes

Adding before checking, or modifying *out when reporting failure.

Edge cases to handle

Positive overflow; negative underflow; exact INT_MIN/INT_MAX boundaries; zero; unchanged output after rejection.

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