The C++ preprocessor – recursive includes
A few posts ago I mentioned trying to calculate factorials using the C/C++ preprocessor. Afterward I remembered back in college trying to use recursive #includes to solve the same problem. My attempt looked something like this.
First I created a file to do the calculation. I’ll call it calc_factorial.h.
// calc_factorial.h # if ( N < 0 ) # error Factorial of negative not allowed # elif ( N == 0 ) # define FACTORIAL 1 # else # define NSAVE N # undef N # define N (NSAVE - 1) # include "calc_factorial.h" # define FSAVE FACTORIAL # undef FACTORIAL # define FACTORIAL (NSAVE * FSAVE) # endif
Then from another file I tried to #include "calc_factorial.h" to do the calculation.
# define N 5 # include "calc_factorial.h" // At this point I hoped FACTORIAL would be 120, // but instead I got a compile error.
Of course this doesn't work, unless N is 0. For other values it reports the #error "Factorial of negative not allowed". Without the (N<0) test it recurses to death, nesting #include "calc_factorial.h" until we hit the stack limit. On all but the first iteration N --> (NSAVE - 1) --> (N - 1) --> (0 - 1) --> -1. Remember that N is undefined when we get to (N - 1) because recursive expansion is not allowed. And #if interprets undefined tokens as zero.
It was a fun experiment anyway.
Comments
Leave a Reply