How to write a while loop with the C preprocessor?

Viewed 73312

I am asking this question from an educational/hacking point of view, (I wouldn't really want to code like this).

Is it possible to implement a while loop only using C preprocessor directives. I understand that macros cannot be expanded recursively, so how would this be accomplished?

7 Answers

Take a look at the Boost preprocessor library, which allows you to write loops in the preprocessor, and much more.

You use recursive include files. Unfortunately, you can't iterate the loop more than the maximum depth that the preprocessor allows.

It turns out that C++ templates are Turing Complete and can be used in similar ways. Check out Generative Programming

I use meta-template programming for this purpose, its fun once you get a hang of it. And very useful at times when used with discretion. Because as mentioned its turing complete, to the point where you can even cause the compiler to get into an infinite loop, or stack-overflow! There is nothing like going to get some coffee just to find your compilation is using up 30+ gigabytes of memory and all the CPU to compile your infinite loop code!

Here's an abuse of the rules that would get it done legally. Write your own C preprocessor. Make it interpret some #pragma directives the way you want.

I found this scheme useful when the compiler got cranky and wouldn't unroll certain loops for me

#define REPEAT20(x) { x;x;x;x;x;x;x;x;x;x;x;x;x;x;x;x;x;x;x;x;}

REPEAT20( val = pleaseconverge(val) );

But IMHO, if you need something much more complicated than that, then you should write your own pre-preprocessor. Your pre-preprocessor could for instance generate an appropriate header file for you, and it is easy enough to include this step in a Makefile to have everything compile smoothly by a single command. I've done it.

Related