Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working of the C Preprocessor

How does the following piece of code work, in other words what is the algorithm of the C preprocessor? Does this work on all compilers?

#include <stdio.h>

#define b a
#define a 170


int main() {
  printf("%i", b);
  return 0;
}
like image 304
shreyasva Avatar asked Dec 07 '22 20:12

shreyasva


2 Answers

The preprocessor just replaces b with a wherever it finds it in the program and then replaces a with 170 It is just plain textual replacement.

Works on gcc.

like image 133
Alok Save Avatar answered Dec 25 '22 12:12

Alok Save


It's at §6.10.3 (Macro Replacement):

6.10.3.4 Rescanning and further replacement

1) After all parameters in the replacement list have been substituted and # and ## processing has taken place, all placemarker preprocessing tokens are removed. Then, the resulting preprocessing token sequence is rescanned, along with all subsequent preprocessing tokens of the source file, for more macro names to replace.

Further paragraphs state some complementary rules and exceptions, but this is basically it.

Though it may violate some definitions of "single pass", it's very useful. Like the recursive preprocessing of included files (§5.1.1.2p4).

like image 26
aib Avatar answered Dec 25 '22 12:12

aib