Home > Net >  What will happen when macro definitions are nested?
What will happen when macro definitions are nested?

Time:09-13

// main.cpp
#define a aa
#define aa a
int main()
{
    int a = 1;
    int aa = 11;
}

As like the code above, the macro definition is nested. Is finally a = 1 or a = 11 ?

CodePudding user response:

C 2018 6.10.3.4 2 discusses rescanning for more macro names after macro replacement and says:

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…

Then, when a is replaced with aa, rescanning finds aa and replaces it with a. Then rescanning does not replace a since it has already been replaced.

Similarly, when aa is replaced with a, rescanning finds a and replaces it with aa. Then rescanning does not replace aa since it has already been replaced.

CodePudding user response:

Well, try running it with gcc -E which runs only the preprocessor. Which outputs the following preprocessed c file.

int main()
{
    int a = 1;
    int aa = 11;
}

This is with all your #defines expanded. Apparently it leaves it as is, or maybe does a limited number of passes.

  •  Tags:  
  • c
  • Related