One-liners

Contents

One-liners#

Macros and expressions the operator reaches for inside a C source file. Each is the canonical short form; reach for an inline function the moment the body needs a statement.

Max and min as type-agnostic macros. Parenthesise every argument to survive operator precedence.

#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define MIN(a, b) ((a) < (b) ? (a) : (b))

Array length, valid only on a real array (not a pointer); fails loudly if applied to a decayed pointer because the result becomes sizeof(ptr) / sizeof(T).

#define ARRAY_LEN(a) (sizeof(a) / sizeof((a)[0]))

Swap two values without a temporary, via XOR (integers only, distinct addresses required).

a ^= b; b ^= a; a ^= b;

Clamp x to [lo, hi] as a macro.

#define CLAMP(x, lo, hi) ((x) < (lo) ? (lo) : (x) > (hi) ? (hi) : (x))

Round-up integer division.

((a) + (b) - 1) / (b)

Test whether an unsigned integer is a power of two.

((x) != 0 && ((x) & ((x) - 1)) == 0)

Set, clear, toggle, and test a single bit.

flags |=  (1u << n);   // set
flags &= ~(1u << n);   // clear
flags ^=  (1u << n);   // toggle
((flags >> n) & 1u)    // test

References#

  • Snippets for the snippets catalogue.

  • Operators for the underlying operators these one-liners build on.