我可以在C程序中的任何地方编写预处理程序指令吗? [英] Can i write preprocessor directives anywhere in my c program?

查看:69
本文介绍了我可以在C程序中的任何地方编写预处理程序指令吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否必须在程序顶部和主要功能之外编写#include?

Is it mandatory to write #include at the top of the program and outside the main function?

我尝试在主函数中使用#define预处理程序,但工作正常,只有一个异常..那是我使用define指令定义的常量,只能使用在#define
行之后,例如说 printf(%d,PI); #define PI 3.14 将给出错误未定义符号PI。但是在以下代码中,我没有遇到任何错误

I tried using #define preprocessor inside the main function and it worked fine with only one exception..that being the constant which i defined using the define directive can be used only after the line #define For instance say printf("%d",PI); #define PI 3.14will give error "Undefined symbol PI". But in the following code i did not encounter any error

#define PI 3.14 
printf("%d",PI);

这是因为C是一种过程语言,而过程语言实现了自上而下的方法?

Is this because C is a procedural language and procedural languages implements top down approach?

我也想知道我们也可以在主函数或其他预处理程序指令中仅使用#define吗?如果我们可以使用那一个呢?
还是相反,可以使用main函数中的所有预处理器指令代替#include?

Also i would like to know that can we use only #define inside the main function or other preprocessor directives too? If we can use then which ones? Or is it the other way around, instead of #include we can use all the preprocessor directives in the main function?

推荐答案

唯一不能放置预处理器指令的位置是宏扩展。唯一的例外是 #pragma ,也可以写为 _Pragma()

The only place you can't put a preprocessor directive is in a macro expansion. The sole exception is #pragma, which can also be written _Pragma().

这与过程式无关,但是由于C是根据8个翻译阶段定义的,每个阶段在下一阶段之前都是按条件完成的。有关更多详细信息,请参见C11标准的5.1.1.2节。

This has nothing to do with "procedural", but due to the fact that C is defined in terms of 8 translation phases, each of which is "as-if" fully-completed before the next phase. For more details, see the C11 standard, section 5.1.1.2.

一个有用的示例有用可以在文件开始后使用预处理器指令进行 X宏技术(许多人仅将其称为那些 .def 文件)。

One example of when it is useful to use preprocessor directives after the start of a file is for the "X Macro" technique (which many people only know as "those .def files").

这篇关于我可以在C程序中的任何地方编写预处理程序指令吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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