Purpose recognition: Is the sequence #ifdef … #else … #endif used for conditional compilation in C/C++?
-
ACorrect
-
BIncorrect
-
COnly for commenting out code blocks
-
DOnly meaningful in headers, not source files
-
EDeprecated in modern compilers
Answer
Correct Answer: Correct
Explanation
Introduction / Context:Conditional compilation is a core technique for portability and feature gating. The directive pattern #ifdef … #else … #endif is one of the most commonly used mechanisms for including or excluding code based on macro definitions.
Given Data / Assumptions:
- #ifdef TEST … #else … #endif compiles the first branch only if TEST is defined; otherwise, the #else branch is kept.
- We assume standard-compliant preprocessor behavior.
Concept / Approach:#ifdef tests for definition, not value. If the macro is defined (via #define or command line like -DTEST), the guarded region is retained in the preprocessor output. The complementary #ifndef tests for non-definition. These controls are resolved before actual compilation, which means disabled code does not reach the compiler.
Step-by-Step Solution:Decide condition: macro present → choose upper branch; absent → choose #else branch (if present).Preprocessor removes the unused branch entirely from the translation unit.Compiler then sees only the selected branch, improving portability and allowing platform- or configuration-specific sections.
Verification / Alternative check:Use a preprocess-only step (-E) to examine that the inactive branch is gone. Alternatively, define/undefine the macro via compiler flags to toggle behavior and observe differing builds.
Why Other Options Are Wrong:“Incorrect” contradicts the standard; “Only for commenting out code” misrepresents conditional inclusion; “Only meaningful in headers” is false—these directives are valid in any source; “Deprecated” is incorrect.
Common Pitfalls:Treating #ifdef like a runtime if; assuming it tests macro values rather than definition; forgetting to close with #endif.
Final Answer:Correct