Recursive function as #define statement

Why does this work:
1
2
3
int factorial(int n){
     return(n==0 ? 1 : n * factorial(n-1));
}

but not this:
 
#define factorial(n) n==0 ? 1 : n * factorial(n-1) 

and is there any way to make the recursive #define statement valid?
preprocessor directives can't be recursive.
Use functions instead of macros, macros are bad
Concur.

And here's the reason why:

From C++ standard -
If the name of the macro being replaced is found during this scan of the replacement list (not including the rest of the source file's pre- processing tokens), it is not replaced. Further, if any nested replacements encounter the name of the macro being replaced, it is not replaced. These nonreplaced macro name preprocessing tokens are no longer available for further replacement even if they are later (re)examined in contexts in which that macro name preprocessing token would otherwise have been replaced.
Last edited on
An explanation of what you're trying to do should make it clear why it can't be done.

The preprocessor does just that, preprocesses the source files before handing them over to the compiler.

The preprocessor takes

#define <Macroname> <replacement text>

And replaces any example of <Macroname> in the source code with <replacement text>. It's not much more than a simple search and replace prior to compilation.

So, in your example, if it found "factorial(x)" in your code, it would replace it with "x==0 ? 1 : x * factorial(x-1)". (the only additional logic built into Macros is to handle parameters passed in, x here instead of n)

If it were to recurse the way you want it to, it would replace the "factorial(x-1)" that it just inserted with "x==0 ? 1 : x * factorial(x-1-1)", then replace it again, and again, without any termination.
Topic archived. No new replies allowed.