用C#定义preprocessor范围 [英] Scope of #define preprocessor in C

查看:79
本文介绍了用C#定义preprocessor范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的#define 的范围,直到文件的末尾。但是,在它的开始。
基本上我尝试了以下code。

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

对于PI的主要价值考虑preprocessing应该是3.141516
外主要3.14。这是不正确,但请解释原因。

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

推荐答案

的C preprocessor通过文件运行顶部至底部和对待的#define 语句就像一个荣耀的复制和粘贴操作。一旦遇到行的#define PI 3.14 ,它开始替换单词的每个实例 PI 3.14 。在pre处理器确实喜欢括号和大括号不是过程(甚至通知)C语言范围界定机制。一旦它看到一个的#define ,这个定义是直到文件无论是最终的效果是达到了,宏是和#undef取消定义,或(在这种情况下)宏观与另一的#define 语句重新定义。

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.

如果你是,我建议使用更多的东西就行想要服从的C作用域规则常量常量浮动PI = 3.14;

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#定义preprocessor范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆