C语言 C中#define预处理器的范围
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6379489/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scope of #define preprocessor in C
提问by Rohit Jain
The scope of #defineis till the end of the file. But where does it start from.
Basically I tried the following code.
的范围#define是直到文件末尾。但它从哪里开始。基本上我尝试了以下代码。
#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.
考虑到 main 的预处理,pi 的值应该是 3.141516 并且在 main 3.14 之外。这是不正确的,但请解释原因。
回答by bta
The C preprocessor runs through the file top-to-bottom and treats #definestatements like a glorified copy-and-paste operation. Once it encounters the line #define pi 3.14, it starts replacing every instance of the word piwith 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 #definestatement.
C 预处理器自上而下运行文件,并将#define语句视为美化的复制和粘贴操作。一旦它遇到的线#define pi 3.14,它开始替换单词的每个实例pi有3.14。预处理器不处理(甚至不注意到)C 语言范围机制,如括号和花括号。一旦它看到 a #define,该定义将一直有效,直到到达文件末尾,宏未定义为#undef,或者(在这种情况下)宏被另一个#define语句重新定义。
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;.
如果您想要遵守 C 范围规则的常量,我建议在const float pi = 3.14;.
回答by Jim Lewis
The scope of a #defineis from the occurrence, to the end of the file, regardless of any intervening C scopes.
a 的范围#define是从出现到文件末尾,而不管任何中间的 C 范围。
回答by jman
When you have preprocessor question:
当您有预处理器问题时:
gcc -E foo.c > foo.i; vim foo.i
gcc -E foo.c > foo.i; vim foo.i
回答by antlersoft
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)
符号从定义到编译单元结束(源文件和它包含的文件)
回答by Chris Frederick
As far as I know, the preprocessor uses #definestatements in the order that it encounters them. In that case, your first printfstatement correctly prints 3.14 and the second 3.141516 (is there a typo in the output from your program?).
据我所知,预处理器#define按照遇到语句的顺序使用语句。在这种情况下,您的第一个printf语句正确打印 3.14 和第二个 3.141516(您的程序输出中是否有拼写错误?)。

