STDCKDINT(3)
πΈ NAME πΈ
okay bestie, meet stdckdint β checked integer arithmetic. This is the STDCKDINT(3) page from the Library Functions Manual, and it's here to keep your integer math from silently going feral. π
β¨ SYNOPSIS β¨
#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);
π¦ DESCRIPTION π¦
The function-like macros ckd_add, ckd_sub, and ckd_mul perform checked integer addition, subtraction, and multiplication, respectively. Like, they're the group chat mods for your arithmetic. π
Here's the tea: if the result of adding, subtracting, or multiplying a and b β as if their respective types had infinite range β fits in type1, it gets stored in the location pointed to by result, and the macro evaluates to false. Slay, no overflow.
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. So yeah, it tells you when things got weird, and gives you the wrapped value. π
π 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. That's the whole vibe check. β¨
π 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;
}
π HISTORY π
The ckd_add, ckd_sub, and ckd_mul macros were first introduced in FreeBSD 14.0. iconic behavior, honestly. π
π AUTHORS π
The ckd_add, ckd_sub, and ckd_mul macros and this manual page were written by Dag-Erling SmΓΈrgrav (<des@FreeBSD.org>). Give them their flowers. π
π this cute little page is sourced from the Debian version of STDCKDINT(3), dated September 5, 2023 β okay bestie, go do checked math and stay safe! π«Ά
π¦ where this page comes from
- freebsd 14.5: base 14.5
- freebsd 15.1: base 15.1
- π the page's license: BSD-2-Clause
- Copyright (c) 2023 Dag-Erling SmΓΈrgrav
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms