Hasty Briefsbeta

Recursive macros in C, demystified (once the ugly crying stops)

17 days ago
  • #preprocessor
  • #C programming
  • #macros
  • C macros do not support recursion easily due to historical design choices and concerns about infinite loops and compile-time issues.
  • The article explores a workaround for implementing recursive macros in C, focusing on counting variadic macro arguments as a practical example.
  • Key challenges include the C preprocessor's 'blue paint' rule, which prevents recursive macro expansion by marking macros as ineligible for further expansion during their own evaluation.
  • A solution involves using indirection and the `EMPTY()` macro trick to postpone evaluation and avoid triggering the recursion prevention mechanism.
  • The final implementation provides a robust way to count macro arguments and demonstrates how to generalize the approach for other compile-time transformations.
  • The article suggests improvements to the C macro system, such as adding built-ins like `__VA_COUNT__` and `__VA_EMPTY__`, to make compile-time programming in C more accessible.