July 19th, 2024

Tail Recursion for Macros in C

The blog discusses tail recursion for macros in C, introducing __VA_TAIL__() to enable real recursion, overcoming inefficiencies of traditional recursive macro calls. It showcases how tail recursion improves processing efficiency in macros.

Read original articleLink Icon
Tail Recursion for Macros in C

In the blog post by Jens Gustedt, the concept of tail recursion for macros in C is discussed. The post explains how the addition of __VA_OPT__ to C23 sparked interest in extending the C preprocessor to include recursion. It introduces the idea of using __VA_TAIL__() to enable real recursion in macros, avoiding the limitations of traditional recursive macro calls. The post highlights the inefficiency of C preprocessor recursion over variadic argument lists due to quadratic complexity and introduces tail recursion as a solution. Tail recursion in macros allows for linear complexity by avoiding individual expansion of elements in the argument list. The post provides examples of how tail recursion can be implemented in macros, showcasing its efficiency in handling argument lists. It also mentions the implementation of this feature in eĿlipsis, a preprocessor tool, which resolves tail recursion into an iteration over the argument list for efficient processing.

Link Icon 3 comments
By @DerekL - 4 months
I was wondering the same thing about making macros optionally recursive. Because if they were recursive, then that feature and `__VA_OPT__` would be enough to make them Turing-complete.
By @pajko - 4 months
An alternative in pure cpp is https://github.com/swansontec/map-macro