C/C++ preprocessor basics: the #ifndef directive tests whether which entity has NOT been previously defined?

Difficulty: Easy

Correct Answer: a macro (preprocessor symbol) has been defined

Explanation:


Introduction / Context:
The C/C++ preprocessor runs before compilation and handles directives like #define, #include, and conditional compilation. #ifndef is commonly used in header guards to ensure a file is processed only once even if included multiple times. Understanding what #ifndef actually tests prevents subtle multiple-definition errors.


Given Data / Assumptions:

  • #ifndef stands for “if not defined”.
  • Defined/undefined status refers to preprocessor macros created with #define or via compiler options.
  • Preprocessor activity occurs before type checking or object instantiation.


Concept / Approach:

  • #ifndef SYMBOL checks whether the macro SYMBOL is not currently defined.
  • Typical pattern: #ifndef HEADER_NAME
    #define HEADER_NAME
    ... header content ...
    #endif
  • It does not test runtime values, class existence, object creation, or namespace declarations.


Step-by-Step Solution:

Identify the entity #ifndef operates on → macros/preprocessor symbols.Relate to header guards that prevent multiple inclusion.Therefore, #ifndef tests whether a macro has been defined; if not, the guarded code is included.


Verification / Alternative check:

Compile a project with and without a macro defined via -DMYFLAG; #ifndef MYFLAG will include code only when MYFLAG is not set.


Why Other Options Are Wrong:

  • Header included: Inclusion is managed via macros in guards, but #ifndef itself checks the macro, not history of inclusion.
  • Runtime variable value: Preprocessor cannot see runtime state.
  • Class instantiation or namespace declaration: These are compile-time language constructs after preprocessing.


Common Pitfalls:

  • Misspelling guard macros, leading to ineffective guards.
  • Confusing #ifdef with #ifndef; the former checks if defined, the latter if not defined.


Final Answer:

a macro (preprocessor symbol) has been defined

Discussion & Comments

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