Conditional compilation with #ifdef – does this program compile and what is printed? #include <stdio.h> int main() { #ifdef NOTE int a; a = 10; #else int a; a = 20; #endif printf("%d ", a); return 0; }

Difficulty: Easy

Correct Answer: Yes — it compiles and prints 20

Explanation:

Introduction / Context:Conditional compilation via #ifdef allows different code to be compiled depending on whether a macro is defined. This example tests whether duplicate declarations occur and what value is printed when the macro is not defined.

Given Data / Assumptions:

  • NOTE is not defined anywhere.
  • Both branches declare int a; and assign distinct values.
  • Only one branch is compiled and the other is discarded.

Concept / Approach:The preprocessor selects exactly one branch: since NOTE is undefined, the #else path is included. In the final translation unit, there is a single definition and assignment of a. There is no duplication because the excluded branch is not part of the compiled code.

Step-by-Step Solution:Preprocess: retain the #else block only.Resulting code defines a and sets a = 20.Print statement outputs 20.

Verification / Alternative check:Add #define NOTE before #ifdef and observe that the output becomes 10. Using a compiler flag that defines a macro (e.g., -DNOTE) also flips the branch.

Why Other Options Are Wrong:Duplicate definition — incorrect because only one branch is compiled. Require prior #define — not required; it simply chooses the #else branch. Prints 10 — would occur only if NOTE were defined.

Common Pitfalls:Declaring variables in both branches but using them outside without consistent types; forgetting that preprocessor removes the inactive branch entirely.

Final Answer:Yes — it compiles and prints 20

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion