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

I know it's wrong, but just out of curiosity, when I compile it I get this weird error:

"B was not declared in this scope".

Why is it so? If this error was because the compiler removes the macro after its substitution then how does the following code worked fine, when B must have been removed before it was made available to A ?

#define B 100
#define A 100+B
main()
{
    int i= B;
    int j =A;
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
cirronimbo
  • 909
  • 9
  • 19

3 Answers3

14

Here's the output of the preprocessor:

gcc -E x.c
# 1 "x.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "x.c"

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

As you can see, it did the substituion. Now comes the compile step which fails because there's no B declared.

The other code is fine, here's the output:

main()
{
    int i= 100;
    int j =100+100;
}
Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
  • 5
    *Preprocessor*, not *precompiler* – Praetorian Aug 05 '12 at 18:10
  • @cirronimbo: if you have visual studio: http://stackoverflow.com/questions/277258/c-c-source-file-after-preprocessing – Karoly Horvath Aug 05 '12 at 20:03
  • @KarolyHorvath: yeah, I saw that, but unfortunately I work on code::blocks 10.5, not on visual studio, and I really have no clue how to generate this preprocessor output even after looking at the above code, in code::blocks. – cirronimbo Aug 06 '12 at 16:16
  • @cirronimbo: that's just an IDE, a front-end. use a command shell, and type the appropriate command for the compiler (gcc/msvc). – Karoly Horvath Aug 06 '12 at 16:42
9

Macro expansion isn't done recursively, if the macro name appears in the replacement text, it isn't expanded again. So with

#define B 100 + B

a replacement of B yields the token sequence 100 + B and B is not expanded again (if it were, you'd have an infinite recursion). So the compiler sees a reference to the undeclared variable B after the preprocessor finished.

But in

#define B 100
#define A 100 + B

when the macro A is expanded, the macro name B appears in the replacement text. Then B is expanded and the compiler sees 100 + 100 which contains no references to undeclared variables.

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
0

macro replacement are simple text operation.you can debug this type of problem in a simple step by step compile.

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

for generate extended c code

vi filename.i for reading pure/extended c code

Johan Lundberg
  • 26,184
  • 12
  • 71
  • 97
rajesh6115
  • 705
  • 9
  • 21