When pre-processing this code:
#define SUM(N) (N + 1 + SUM##N)
#define SUM10 SUM(9)
#define SUM9 SUM(8)
#define SUM8 SUM(7)
#define SUM7 SUM(6)
#define SUM6 SUM(5)
#define SUM5 SUM(4)
#define SUM4 SUM(3)
#define SUM3 SUM(2)
#define SUM2 SUM(1)
#define SUM1 SUM(0)
#define SUM0 0
int sum = SUM10;
the preprocessor seems to halt as soon as it detects the indirect recursion. Why?
A function-like macro definition specifies a set of tokens that will
replace the thing that looks like a function call, with variable
substitution and # and ## processing.
"After all parameters in the replacement list have been substituted and
# and ## processing has taken place, ... The resulting preprocessing
token sequence is then rescanned, along with all subsequent
preprocessing tokens of the source file, for more macro names to replace.
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
preprocessing tokens), it is not replaced. Furthermore, 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." (6.10.3.4p1-2)
The Rationale explains why they decided to make such a rule:
"A problem faced by many pre-C89 preprocessors is how to use a macro
name in its expansion without suffering “recursive death.” The C89
Committee agreed simply to turn off the definition of a macro for the
duration of the expansion of that macro."
I've no idea whether the following kind of macro definition played any
role in their decision, but it would not work if macros were allowed to
be recursive:
header.h:
int func(double x);
caller.c:
#include "header.h"
unsigned long func_calls = 0;
#define func(x) (func_calls++,func(x))