Simvik

Macros that survive any argument

Fix three helper macros so they work with expressions and side effects. A medium embedded C problem (Inline functions and macros), run and graded in the…

medium · Inline functions and macros · macros · inline · preprocessor

Function-like macros paste their arguments as text, which causes two classic bugs: missing parentheses (SQUARE(a + 1) becomes a + 1 * a + 1) and arguments evaluated twice (MAX(x++, y) increments x twice).

Fix the starter:

  • ARRAY_LEN(a): the number of elements in an array,
  • IS_POW2(x): 1 if x is a non-zero power of two, else 0, correct for expressions such as 4 + 4,
  • replace the CLAMP macro with a static inline int clamp_int(int x, int lo, int hi) function, so each argument is evaluated once.

Starter code

#define ARRAY_LEN(a) sizeof a / sizeof a[0]
#define IS_POW2(x) x && !(x & x - 1)
#define CLAMP(x, lo, hi) ((x) < (lo) ? (lo) : (x) > (hi) ? (hi) : (x))

static inline int clamp_int(int x, int lo, int hi) {
  return CLAMP(x, lo, hi);
}

Example tests

Array length

uint16_t buf[12];
printf("%d\n", (int)ARRAY_LEN(buf));

Expected output:

12

Powers of two from expressions

printf("%d %d %d %d\n", IS_POW2(8), IS_POW2(4 + 4), IS_POW2(6), IS_POW2(0));
printf("%d\n", 2 * IS_POW2(16));

Expected output:

1 1 0 0
2

Learn it first

More Inline functions and macros problems