The snippet library.
Small, practical examples. Search by task or narrow things down below.
Calculate a page count without an overflowing addition
C: Divide first and add one only when a nonzero remainder remains.
C✓ Tested
Check positive integer addition before performing it
C: Check the upper boundary before adding two known nonnegative integers.
C✓ Tested
Clamp an integer to inclusive bounds
C: Explicit comparisons avoid relying on nonstandard min or max macros.
C✓ Tested
Compare small floating-point results with a tolerance
C: Use an absolute difference threshold for this known bounded magnitude.
C✓ Tested
Compute a two-dimensional vector length
C: hypot avoids unnecessary intermediate overflow compared with squaring both inputs directly.
C✓ Tested
Parse an unsigned hexadecimal integer
C: Use an explicit base and check both range and full consumption.
C✓ Tested
Reject NaN and infinite values
C: isfinite detects whether a floating-point value is an ordinary finite number.
C✓ Tested
Round a halfway floating-point value
C: The C round function rounds halfway cases away from zero.
C✓ Tested
Round downward and upward independently
C: floor and ceil round toward negative and positive infinity respectively.
C✓ Tested
Validate a complete floating-point input
C: strtod exposes both the stopping position and range errors; reject nonfinite results when required.
C✓ Tested