c - Macro behavior in function -


i expected output below program 10 20 10 10.

#include <stdio.h> #define 10  int main() { printf("%d\t",i); fun(); printf("%d",i); return 0; }  fun(){     #undef     #define 20 } 

if assume if function call fun() returned main() original i value printed again wrong looking @ output below program,

#include <stdio.h> #define 10  fun(){     #undef     #define 20 }  int main() { printf("%d\t",i); fun(); printf("%d",i); return 0; } 

expected output: 10 20 output is: 20 20

can please explain me behaviour?

the #define preprocessor macro. value substituted @ compile time instead of runtime.

so, processing happens per presence (sequence) of #defines. means, cannot expect #undef , #define work on runtime.

to elaborate, case 1 code looks like

#include <stdio.h> #define 10  int main() { printf("%d\t",10); fun(); printf("%d",10); return 0; }  fun(){     #undef     #define 20 }//now 20, no 1 using it, @ compile time 

and, second code looks like

#include <stdio.h> #define 10  fun(){     #undef     #define 20   // new definition here }  int main() { printf("%d\t",20); fun(); printf("%d",20); return 0; } 

a note: recommended signature of main() int main(void).


Comments