ksb
ksb

Reputation: 710

Scope of #define in a single main file

I know that probably there is no concept of scope for macros, but please help me understand the following output - which seems to suggest that macros are local to functions:

#include<stdio.h>
#include<stdlib.h>
#define A 100
void fun();
int main()
{

    fun();
    printf("%d\n",A);
    system("pause");
    return 0;
}
void fun()
{
    #undef A

}

The output of the program is 100 though according to me it should have been a compiler error. Please explain why?

Upvotes: 0

Views: 372

Answers (5)

pizza
pizza

Reputation: 7640

macro expansion is done at preprocessing step, which is a step before compiling. If you like to see how the code looks after this step, try compile with preprocessing only option.

e.g.

gcc -E myfile.c > myfile.ppout

and read the output.

Upvotes: 0

user1131435
user1131435

Reputation:

You can't run preprocessor commands in functions. They're removed from compiled code. That's why they're called preprocessor: they are executed and removed before the program is compiled. In fun(), you are undefining the number 100.

Upvotes: 1

DigitalRoss
DigitalRoss

Reputation: 146231

The preprocessor makes a single pass though the program text at compile time. By the time the program runs all of the directives are long gone.

Originally, the preprocessor was actually a separate program that understood C only to the extent that it parsed tokens the same way. After creating a macro-expanded version of the program as a temporary file, the real compiler was run. Today, it's integrated into the compiler, but in such a way that the effect is the same.

This is how the convention of using all-upper-case macro names began, i.e., in order to emphasize their substantially different nature. You can still get the compiler to output the expanded-but-uncompiled intermediate text. This is occasionally useful when tracking down bugs and understanding complicated conditional compilation.

Upvotes: 1

The pre-processor works on the text of your source code and it does it before the compiler proper ever starts to run.

In essence your compiler works on a file that looks like

/* Lots of code from the included files omitted */
void fun();
int main()
{

    fun();
    printf("%d\n",100);
    system("pause");
    return 0;
}
void fun()
{

}

So running and printing 100 is exactly what you would expect.

Notice that all the pre-processor directives are gone, and that all instances of A between the define and the undef have been replaced with 100.

The thing to remember is:

  • The pre-processor runs, changing the text
  • Then the compiler runs on the result

Upvotes: 2

Chriseyre2000
Chriseyre2000

Reputation: 2053

Macros are executed at compile time (in fact before the compiler).

Upvotes: 0

Related Questions