Simvik

Checked signed addition

Add two int32t values and report overflow without invoking undefined behaviour. A medium embedded C problem (Integers and data types), run and graded in the…

medium · Integers and data types · overflow · undefined-behaviour

Signed overflow is undefined behaviour in C, so you cannot add first and check afterwards.

If a + b fits in an int32_t, store it in *out and return true. Otherwise leave *out untouched and return false. Use 32-bit arithmetic only.

Starter code

bool safe_add(int32_t a, int32_t b, int32_t *out) {
  // Decide whether a + b would overflow BEFORE adding.
  *out = a + b;
  return true;
}

Example tests

Fits

int32_t r = -1;
bool ok = safe_add(2, 3, &r);
printf("%d %d\n", ok, r);

Expected output:

1 5

Positive overflow

int32_t r = -1;
bool ok = safe_add(INT32_MAX, 1, &r);
printf("%d %d\n", ok, r);

Expected output:

0 -1

Learn it first

More Integers and data types problems