I am confused between the if/else and #if/#else/#endif constructs.
- What are the differences between them?
- In which specific situations should I use each of them?
On
if(...) and else(...) conditions are evaluated at runtime. #if, #else are evaluated before compile time by the preprocessor.
On
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).
#if,#elseand#endifbelong 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.ifandelseare run-time constructs. You can think of them as being executed while the program runs.Let's say you have this program:
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:
Now, technically you could use an
ifhere:But in C++ you don't use
#definefor constants. You'd instead have something like: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 useif:A good guideline for a beginner would be: Use
#if(or actually:#ifndef) only for include guards. Consider further uses of#ifwhen you encounter problems that can only be solved by the preprocessor.