The snippet library.
Small, practical examples. Search by task or narrow things down below.
Calculate an average without integer division truncation
C: Accumulate into double and divide by the nonzero number of readings.
C✓ Tested
Calculate the greatest common divisor
C: Euclid’s algorithm repeatedly replaces a pair with the divisor and remainder.
C✓ Tested
Call a library function
C: Use a standard absolute-value function with a small negative number.
C✓ Tested
Check a literal filename suffix
C: Check lengths before subtracting so a short input cannot produce an invalid pointer.
C✓ Tested
Check a literal string prefix
C: strncmp compares at most the prefix length; both inputs must be valid strings.
C✓ Tested
Check an array allocation size before multiplying
C: Compare the requested element count against SIZE_MAX divided by element size.
C✓ Tested
Check positive integer addition before performing it
C: Check the upper boundary before adding two known nonnegative integers.
C✓ Tested
Choose between two branches
C: Use if and else to handle an available or empty stock count.
C✓ Tested
Clamp an integer to inclusive bounds
C: Explicit comparisons avoid relying on nonstandard min or max macros.
C✓ Tested
Clear an owning pointer after releasing its allocation
C: Assigning NULL helps prevent accidental reuse through the same variable.
C✓ Tested
Combine text with a name
C: Construct a greeting from a fixed prefix and a stored name.
C✓ Tested
Compare a value with a limit
C: Turn a comparison into a readable yes or no result.
C✓ Tested