Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a preprocessor macro work?

#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;
}
like image 632
cirronimbo Avatar asked Aug 05 '12 18:08

cirronimbo


1 Answers

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;
}
like image 136
Karoly Horvath Avatar answered Nov 15 '22 07:11

Karoly Horvath