I am confused between the if
/else
and #if
/#else
/#endif
constructs.
Can I ask what's the differences between them?
#if
#else
and #endif
are instructions to the compiler, to only compile the code between them, if a compilation level condition (like a macro being defined or having a certain value) is satisfied.
if
and else
are parts of the compiled algorithm.
What kind of specific situations for me to choose each of them?
The pre-compilation conditions are used to disable parts of the code, in situations where they make no sense (like calls to Windows-specific APIs, when compiling under Linux). They are key to developing cross-platform code (for example).
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
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
and else
are run-time constructs. You can think of them as being executed while the program runs.
Let's say you have this program:
#include <iostream>
#define VALUE 1
int main()
{
#if VALUE == 1
std::cout << "one\n";
#else
std::cout << "not one\n";
#endif
}
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";
}
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";
}
}
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";
}
}
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?
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(...)
and else(...)
conditions are evaluated at runtime. #if
, #else
are evaluated before compile time by the preprocessor.