简体   繁体   中英

Scope of #define preprocessor in C

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.

The C preprocessor runs through the file top-to-bottom and treats #define statements like a glorified copy-and-paste operation. Once it encounters the line #define pi 3.14 , it starts replacing every instance of the word pi with 3.14 . The pre-processor does not process (or even notice) C-language scoping mechanisms like parenthesis and curly braces. Once it sees a #define , that definition is in effect until either the end of the file is reached, the macro is un-defined with #undef , or (as in this case) the macro is re-defined with another #define statement.

If you are wanting constants that obey the C scoping rules, I suggest using something more on the lines of const float pi = 3.14; .

#define的范围是从出现到文件末尾(或相应的#undef ),而不管任何中间的 C 范围。

When you have preprocessor question:

gcc -E foo.c > foo.i; vim foo.i

Preprocessor has no concept of "scope" -- it manipulates the text of the program, without any idea of what the text is

Symbol is defined from its definition until the end of the compilation unit (a source file and and files it includes)

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.

As far as I know, the preprocessor uses #define statements in the order that it encounters them. In that case, your first printf statement correctly prints 3.14 and the second 3.141516 (is there a typo in the output from your program?).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM