Saturating addition without overflowing signed C integers
A scaled sensor reading or accumulated control value may have a specified representable range. If the design intends a clamp, the result should stop at the endpoint rather than wrap around. Signed C overflow is undefined, so calculating the overflowing expression first and then comparing it is not a valid approach. Use an intermediate whose range has been justified.
The contract
For two int16_t inputs, int32_t holds their mathematical sum. This means the addition can be performed in a wider signed type and compared with the destination bounds before converting. Other widths or operations may require checked arithmetic instead of a wider type. Make sure the specified clamp matches the application rather than merely the storage type.
A small executable example
#include <stdint.h>
#include <assert.h>
#include <stdio.h>
static int16_t add_sat(int16_t a, int16_t b) {
int32_t s = (int32_t)a + (int32_t)b;
if (s > INT16_MAX) return INT16_MAX;
if (s < INT16_MIN) return INT16_MIN;
return (int16_t)s;
}
int main(void) {
assert(add_sat(INT16_MAX, 1) == INT16_MAX);
assert(add_sat(INT16_MIN, -1) == INT16_MIN);
assert(add_sat(-1, 1) == 0);
assert(add_sat(100, 200) == 300);
puts("saturation checked");
}
saturation checked
Compiled with -Wall -Wextra -Werror and run under AddressSanitizer + UBSan.
Learning this for work or an interview? Lessons 1 and 2 of DSA for Firmware are free, with labs and C exercises. Start Lesson 1
What the example does not establish
The example chooses the full destination range. A real application may use a narrower physical range or report saturation separately. Some hardware offers saturating instructions, but those instructions and compiler intrinsics are target-specific. The portable function gives a reference behavior to compare against any optimized target implementation. If saturation is a fault condition, document how the caller learns about it.
Checks to add in your own project
Test the endpoints and values one unit on either side of the intended limit. Compare an optimized function against a mathematical reference over a broad set of inputs, including opposite signs. In a time-sensitive loop, measure latency and jitter on target hardware. Ensure the chosen behavior remains correct even when a compiler performs aggressive optimizations.
DSA for Firmware teaches it one real bug at a time.
- 28 lessons, each starting from a real firmware bug.
- 110 C exercises with tests, and a reference solution for every one.
- Lessons 1 and 2 are free. No sign-up.
Get the next article by email
One short email when a new article or free lesson is published. No spam. Unsubscribe at any time by replying to any email. See the privacy policy.