How does the preprocessor macro work?

#define B 100+B main() { int i= B; } 

I know this is wrong, but just out of curiosity, when I compile it, I get this strange error:

"B has not been announced in this area."

Why is that? If this error occurred because the compiler deletes the macro after replacing it, how does the following code work when B had to be deleted before it was available for A?

 #define B 100 #define A 100+B main() { int i= B; int j =A; } 
+6
source share
3 answers

Here is the output of the preprocessor:

 gcc -E xc # 1 "xc" # 1 "<built-in>" # 1 "<command-line>" # 1 "xc" main() { int i= 100+B; } 

As you can see, this has replaced. Now comes the compilation phase, which fails because B not declared.

Another code is ok, here is the output:

 main() { int i= 100; int j =100+100; } 
+14
source

Macro expansion is not performed recursively, if the macro name appears in the replaced text, it no longer extends. So,

 #define B 100 + B 

replacing B gives a token sequence of 100 + B and B does not expand again (if that were the case, you would have infinite recursion). Thus, the compiler sees a reference to the undeclared variable B after the preprocessor completes.

But in

 #define B 100 #define A 100 + B 

when macro A is expanded, macro B will appear in the replacement text. Then B expands and the compiler sees 100 + 100 , which does not contain references to undeclared variables.

+9
source

replacing macros is a simple text operation. You can debug this type of problem in a simple step-by-step compilation.

use cc -E filename.c -O filename .i

to generate extended c code

vi filename.i to read pure / extended c code

0
source

Source: https://habr.com/ru/post/922172/


All Articles