<stdckdint.h> provides checked arithmetic macros (C23): ckd_add, ckd_sub, ckd_mul. They perform the operation and return true if overflow occurred, false otherwise, without triggering undefined behavior.
Use these instead of manual overflow checks for cleaner, safer code.
This example demonstrates overflow detection for addition and multiplication.
// compile: gcc -std=c2x -o stdckdintexample stdckdintexample.c // run: ./stdckdintexample // description: checked arithmetic detecting overflow #include <stdckdint.h> #include <limits.h> #include <stdio.h> int main() { int result; if (ckd_add(&result, INT_MAX, 1)) { printf("INT_MAX + 1 overflows\n"); } long product; if (ckd_mul(&product, 1000000L, 1000000L)) { printf("1000000 * 1000000 overflows long\n"); } else { printf("product = %ld\n", product); } return 0; }
Checked arithmetic (return true on overflow, result stored in first arg):
ckd_add(result_ptr, a, b): checked additionckd_sub(result_ptr, a, b): checked subtractionckd_mul(result_ptr, a, b): checked multiplicationAll three macros:
result_ptr