You know how C++ programmers are always bragging about how you can do things like compute factorials at run-time with templates? Well, C++'s template system is nothing but a glorified preprocessor, and here's evidence. Try it with something like gcc -w -DN=11 fact.c -o fact.
#ifndef INITIALIZED #define INITIALIZED #ifndef N #define N 11 #endif #define A ((N)&1) #define B ((N)>>1&1) #define C ((N)>>2&1) #define D ((N)>>3&1) int main(void) { printf("fact(%d) = %d", N, #include __FILE__ ); } #else /* INITIALIZED */ (8*D + 4*C + 2*B + A) #if A #define A 0 #else #define A 1 #if B #define B 0 #else #define B 1 #if C #define C 0 #else #define C 1 #if D #define D 0 #endif #endif #endif #endif #if A || B || C || D * #include __FILE__ #endif #endif
Credit where credit is due: the idea comes from the IOCCC entry that does Towers of Hanoi with the preprocessor.
For our next example, we'll show how you can generate code for a 256-point FFT with the preprocessor.
(to be continued)