8

How many passes does the C preprocessor make over the code?

I tested following code on gcc 4.7.2

#define a 5
#define b a
#define c b
#define d c
#define e d
#define f e
#define g f
#define h g
#define j h
#define k j
#define l k
#define m l

int main(void) {return d;}

There is no error:

$ gcc -E 1.c
# 1 "1.c"
# 1 "<command-line>"
# 1 "1.c"
# 14 "1.c"
int main(void) {return 5;}

Is it standard behaviour?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278

1 Answers1

15

The C preprocesor keeps going until there's nothing more to expand. It isn't a question of passes; it's a question of completeness.

It does avoid recursive expansion of macros. Once a macro has been expanded once, it is not re-expanded in the replacement text.


The only thing the standard says about limits on macro expansion is in §5.2.4.1 Translation limits, where it says:

The implementation shall be able to translate and execute at least one program that contains at least one instance of every one of the following limits:18)

...

  • 4095 macro identifiers simultaneously defined in one preprocessing translation unit

18) Implementations should avoid imposing fixed translation limits whenever possible.

So, the preprocessor must be able to handle at least 4095 macros, and if all but one of those macros expand to another macro sequentially, like in your example, the result must be correct.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278