Scope of #define preprocessor in C

Viewed 27668

The scope of #define is till the end of the file. But where does it start from. Basically I tried the following code.

 #include<stdio.h>
 #include<stdlib.h>
 #define pi 3.14
 void fun();
 int main()
{
 printf("%f \n",pi);
 #define pi 3.141516
    fun();
return 0;
}
void fun(){
printf("%f \n",pi);}

The output of the above program comes out to be

3.140000
3.141416

Considering preprocessing for main the value of pi should be 3.141516 and outside main 3.14. This is incorrect but please explain why.

6 Answers

Here is what roughly looks like after the preprocessor done with your file:

 void fun();
 int main()
 {
    printf("%f \n",3.14);
   
    fun();
    return 0;
 }
 void fun(){
 printf("%f \n",3.141516);}

These are the lines that go to the compiler for compilation(I discarded many of the codes for the sake of clarity, only kept what you coded). As the preprocessor replaces the #define directive with the text/value you provided thus you don't see the #define directives anymore after preprocessing. So it is clear what is going to be printed on the console/terminal.

Related