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; } 
4
  • 4
    That’s invalid C++, by the way. Commented Aug 5, 2012 at 18:10
  • 3
    Placing spaces on only one side of the = operator is so ugly… Commented Aug 5, 2012 at 18:14
  • 2
    @RadekSlupik But at least they're on different sides in the two lines, which makes it look kind of funny. Commented Aug 5, 2012 at 18:15
  • 2
    @Daniel Fischer: then perhaps you will like this one: blog.aerojockey.com/post/iocccsim Commented Aug 5, 2012 at 18:25

3 Answers 3

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; } 
Sign up to request clarification or add additional context in comments.

4 Comments

Preprocessor, not precompiler
@cirronimbo: if you have visual studio: stackoverflow.com/questions/277258/…
@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: that's just an IDE, a front-end. use a command shell, and type the appropriate command for the compiler (gcc/msvc).
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.

1 Comment

This answer should get a tick. Just sayin'.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.