Site Tools


h-stdckdint

Table of Contents

<stdckdint.h>

<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.

Example

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;
}

Common macros

Checked arithmetic (return true on overflow, result stored in first arg):

  • ckd_add(result_ptr, a, b): checked addition
  • ckd_sub(result_ptr, a, b): checked subtraction
  • ckd_mul(result_ptr, a, b): checked multiplication

All three macros:

  • Store the result (if no overflow) at result_ptr
  • Return non-zero (true) if overflow occurred
  • Return 0 (false) if no overflow
  • Never trigger undefined behavior even on overflow
h-stdckdint.md · Last modified: by 127.0.0.1