stdckdint(3)

stdckdint3

Checked integer arithmetic

Usage

#include <stdckdint.h>

bool

ckd_add(type1 *result, type2 a, type3 b);

bool

ckd_sub(type1 *result, type2 a, type3 b);

bool

ckd_mul(type1 *result, type2 a, type3 b);

Overview

The function-like macros ckd_add, ckd_sub, and ckd_mul perform checked integer addition, subtraction, and multiplication, respectively. If the result of adding, subtracting, or multiplying a and b as if their respective types had infinite range fits in type1, it is stored in the location pointed to by result and the macro evaluates to false. Otherwise, the macro evaluates to true and the contents of the location pointed to by result is the result of the operation wrapped to the range of type1.

Return values

The ckd_add, ckd_sub, and ckd_mul macros evaluate to true if the requested operation overflowed the result type and false otherwise.

Examples

#include <assert.h>
#include <limits.h>
#include <stdckdint.h>
int main(void)
{
	int result;
	assert(!ckd_add(&result, INT_MAX, 0));
	assert(result == INT_MAX);
	assert(ckd_add(&result, INT_MAX, 1));
	assert(result == INT_MIN);
	assert(!ckd_sub(&result, INT_MIN, 0));
	assert(result == INT_MIN);
	assert(ckd_sub(&result, INT_MIN, 1));
	assert(result == INT_MAX);
	assert(!ckd_mul(&result, INT_MAX / 2, 2));
	assert(result == INT_MAX - 1);
	assert(ckd_mul(&result, INT_MAX / 2 + 1, 2));
	assert(result == INT_MIN);
	return 0;
}

Releases

9 releases since FreeBSD 14.0-RELEASE; the text changed 1 time.

  1. 14.0–15.1
  2. 16.0

History

The ckd_add, ckd_sub, and ckd_mul macros were first introduced in FreeBSD 14.0.

Authors

The ckd_add, ckd_sub, and ckd_mul macros and this manual page were written by Dag-Erling Smørgrav ⟨[email protected]⟩.

From base 16.0-CURRENT-20261027-61c70dc16a79 in FreeBSD 16.0-CURRENT (2026-10-27). Parsed by carta from the page's mdoc source.