if else和#if #else #endif之间的区别 [英] The differences between if else and #if #else #endif
问题描述
在 if
/ else
和 #if
/ #else
/#之间,我感到困惑endif
构造.
- 它们之间有什么区别?
- 在每种情况下我都应该使用它们?
推荐答案
我对if/else和#if/#else/#endif感到困惑.看起来它们具有相同的逻辑功能.
I am confused about the if/else and #if/#else/#endif. It seems that they have the same logic functionality.
请问它们之间有什么区别?
Can I ask what's the differences between them?
#if
, #else
和 #endif
属于预处理.它们未执行,但是文本替换的说明.您可以将它们视为通常在文本编辑器中发现的一种自动搜索与替换"功能.
#if
, #else
and #endif
belong to preprocessing. They are not executed but are instructions for textual replacement. You can think of them as a kind of automatic "search & replace" feature you'd usually find in a text editor.
if
和 else
是运行时结构.您可以认为它们是在程序运行时执行的.
if
and else
are run-time constructs. You can think of them as being executed while the program runs.
假设您有此程序:
#include <iostream>
#define VALUE 1
int main()
{
#if VALUE == 1
std::cout << "one\n";
#else
std::cout << "not one\n";
#endif
}
当您告诉编译器编译该程序时,预处理器将在实际编译真实" C ++代码之前进行文本替换.好像程序是:
When you tell your compiler to compile this program, the preprocessor will make a textual replacement before the "real" C++ code is actually compiled. It will be as if the program was:
#include <iostream>
int main()
{
std::cout << "one\n";
}
现在,从技术上讲,您可以在此处使用 if
:
Now, technically you could use an if
here:
#include <iostream>
#define VALUE 1
int main()
{
if (VALUE == 1)
{
std::cout << "one\n";
}
else
{
std::cout << "not one\n";
}
}
但是在C ++中,您不要对常量使用 #define
.相反,您会有类似的东西:
But in C++ you don't use #define
for constants. You'd instead have something like:
#include <iostream>
int const value = 1;
int main()
{
if (value == 1)
{
std::cout << "one\n";
}
else
{
std::cout << "not one\n";
}
}
也许只有在程序执行时才知道该值,例如通过用户输入.那么您显然不能使用 #if
,它仅在程序运行之前起作用.您必须使用 if
:
Perhaps the value is only known while the program executes, e.g. via user input. Then you obviously cannot use #if
, which only works before the program runs. You must use if
:
#include <iostream>
int main()
{
int value;
std::cin >> value; // gross simplification here
if (value == 1)
{
std::cout << "one\n";
}
else
{
std::cout << "not one\n";
}
}
What kind of specific situations for me to choose each of them?
对于初学者来说,一个好的指导方针是:仅将 #if
(或实际上: #ifndef
)用于
A good guideline for a beginner would be: Use #if
(or actually: #ifndef
) only for include guards. Consider further uses of #if
when you encounter problems that can only be solved by the preprocessor.
这篇关于if else和#if #else #endif之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!