views:

4012

answers:

5

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?

Thanks

+7  A: 

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

Glomek
+3  A: 

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.

Windows programmer
+3  A: 

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

CesarB
A: 
Kevin Beck
+1  A: 

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!

Robert Gould