C Programming Basics
#define DEBUG 0
#ifdef DEBUG
printf("A\n");
#endif
#if DEBUG
printf("B\n");
#endifWhich of the following is the output when the code above is written inside the main function and executed?
- AOnly A is printed
- BNothing is printed
- CA and B are printed
Show answer and explanation
Answer: A. Only A is printed
#ifdef DEBUG only checks whether a macro named DEBUG is defined, not its value. DEBUG is defined with the value 0, so the condition is true and the statement printing A is compiled. #if DEBUG checks the value, which is 0, so it is false and the statement printing B is removed. When switching debug code on and off, mismatches like this occur unless it is consistent whether #ifdef or #if is used for the test.
- A. Correct. #ifdef checks only whether it is defined, and #if checks the value.
- B. #ifdef is true whenever the macro is defined, even with the value 0.
- C. #if DEBUG is false because the value of DEBUG is 0, so the statement for B is removed.