Semantics check: Can #undef be applied only to a macro that was previously #define’d?

Difficulty: Easy

Correct Answer: Incorrect

Explanation:


Introduction / Context:
Maintaining large codebases often requires ensuring a macro is not defined, regardless of prior state. The #undef directive provides that guarantee, and its exact semantics matter for portable build scripts and headers.



Given Data / Assumptions:

  • We consider standard-preprocessor behavior for #undef.
  • The statement claims #undef is valid only if a prior #define existed.


Concept / Approach:
The directive #undef removes any existing definition of a macro name. If the macro is not currently defined, #undef simply ensures the name is undefined; this is not an error. This allows defensive coding patterns such as #undef NDEBUG before redefining it based on build settings.



Step-by-Step Solution:
Start with macro possibly defined or not.Apply #undef NAME.Result: NAME is guaranteed to be not defined, with no diagnostic required.Optionally follow with a new #define NAME … to reset the value as needed.


Verification / Alternative check:
Preprocess a file containing only #undef FOO and observe that no error is produced. Add #ifdef FOO checks to confirm it is undefined afterward.


Why Other Options Are Wrong:
“Correct” contradicts the allowed behavior; restrictions to function-like macros or same-file use are not in the standard; “compiler dependent” is misleading—conforming preprocessors accept #undef on names whether previously defined or not.



Common Pitfalls:
Confusing #undef with language-level deletion (there is none); forgetting that macro scope is translation-unit wide after preprocessing; attempting to #undef keywords or identifiers that are not macros (which has no effect).



Final Answer:
Incorrect

Discussion & Comments

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