vidya
vidya

Reputation: 103

Macro behavior in function

I expected output for the below program as 10 20 but it is 10 10.

#include <stdio.h>
#define i 10

int main()
{
printf("%d\t",i);
fun();
printf("%d",i);
return 0;
}

fun(){
    #undef i
    #define i 20
}

If I assume like if a function call fun() returned back to main() then the original i value is printed then again I am wrong by looking at the output the below program,

#include <stdio.h>
#define i 10

fun(){
    #undef i
    #define i 20
}

int main()
{
printf("%d\t",i);
fun();
printf("%d",i);
return 0;
}

Expected output: 10 20 but the output is: 20 20

Can anybody please explain me the behaviour?

Upvotes: 1

Views: 91

Answers (2)

Sourav Ghosh
Sourav Ghosh

Reputation: 134396

The #define is a preprocessor MACRO. The value is substituted at compile time instead of runtime.

So, the processing happens as per the presence (sequence) of the #defines. That means, you cannot expect the #undef and #define to work on runtime.

To elaborate, your case 1 code looks like

#include <stdio.h>
#define i 10

int main()
{
printf("%d\t",10);
fun();
printf("%d",10);
return 0;
}

fun(){
    #undef i
    #define i 20
}//now i is 20, but no one is using it, at compile time

and, your second code looks like

#include <stdio.h>
#define i 10

fun(){
    #undef i
    #define i 20   // i get a new definition here
}

int main()
{
printf("%d\t",20);
fun();
printf("%d",20);
return 0;
}

A note: The recommended signature of main() is int main(void).

Upvotes: 1

RedX
RedX

Reputation: 15184

One of the very first steps when compiling is to replace all the PREPROCESSING TOKENS with their value. So the evaluation is done at compile time, not at run-time.

So what you get for your first example is:

#include <stdio.h>

int main()
{
  printf("%d\t",10); // we have only seen define i 10 until now
  fun();
  printf("%d",10); // we have only seen define i 10 until now
  return 0;
}

fun(){
  // the two in here would have made any i after this location be replaced with 20
}

And similar for your second case.

Upvotes: 1

Related Questions