Difference between preprocessor directive #if and normal if

删除回忆录丶 提交于 2019-12-18 14:05:43

问题


What is difference between preprocessor directive #if and normal if in C? I'm new to C.


回答1:


Statements with # in front of them are called preprocessor directives. They are processed by a parser before the code is actually compiled. From the first search hit using Google (http://www.cplusplus.com/doc/tutorial/preprocessor/):

Preprocessor directives are lines included in the code of our programs that are not program statements but directives for the preprocessor. These lines are always preceded by a hash sign (#). The preprocessor is executed before the actual compilation of code begins, therefore the preprocessor digests all these directives before any code is generated by the statements.

So a #if will be decided at compile time, a "normal" if will be decided at run time. In other words,

#define TEST 1
#if TEST
printf("%d", TEST);
#endif

Will compile as

printf("%d", 1);

If instead you wrote

#define TEST 1
if(TEST)
printf("%d", TEST);

The program would actually compile as

if(1)
printf("%d", 1);



回答2:


Preprocessor if allows you to condition the code before it's sent to the compiler. normally used to stop header code from being added twice.

edit, did you mean C++, because it was tagged as such? http://www.learncpp.com/cpp-tutorial/110-a-first-look-at-the-preprocessor/




回答3:


The preprocessor if is handled by the preprocessor as the first step in the program being compiled. The normal if is handled at runtime when the program is executed. The preprocessor directive is used to enable conditional compilation, using different sections of the code depending on different defined preprocessor constants/expressions. The normal if is used to control flow in the executing program.



来源:https://stackoverflow.com/questions/5176065/difference-between-preprocessor-directive-if-and-normal-if

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!