Sunny Lei
Sunny Lei

Reputation: 181

Define macro value in function

Below two programs give different results. I thought these two program should give the same result as 20..20 because macro define is in the fun(), it should not affect outside of fun(). Can you explain the reasons?

A: result is 20..20

# include <stdio.h>
# define i 20
void fun();
main()
{
    printf("%d..", i);
    fun();
    printf("%d", i);
}

void fun()
{
    #undef i 
    #define i 30 
}

B: result is 30..30

# include <stdio.h>
# define i 20

void fun()
{
#undef i 
#define i 30 
}

main()
{
    printf("%d..", i);
    fun();
    printf("%d", i);
}

Upvotes: 2

Views: 1981

Answers (2)

CIsForCookies
CIsForCookies

Reputation: 12847

The C Preprocessor is not a part of the compiler, but is a separate step in the compilation process.

Now, because it's a separate step in the compilation process, it's not the same as assigning i with different values. When your code runs, it treats i as 20 because that was defined before main. But, as I said,it's a separate step, and it does not care about functions scope, so, there is before main (i=20) and after main (i=30). When the Preprocessor runs it treats the whole scope as global.

Try using the #define inside the main, not in a function, and check what happens...

Example:

void f(){
    #define a 5
    printf("%d\n", a);
    #undef a
    #define a 10
    printf("%d\n", a);
}

int main()
{
    printf("%d\n", a); // a can be printed even though f() was never called!!
    #define i 20
    printf("%d\n", i); // 20
    #undef i
    #define i 30
    printf("%d\n", i); // 30! :)
    return 0;
}

You can find more info in this Q&A

Upvotes: 5

0___________
0___________

Reputation: 68089

defines are preprocessed before the compilation and they are global. If you want to assign a value in the function just use normal C assign operator & the a global variable,.

Upvotes: 0

Related Questions