C Programming Basics

#define DEBUG 0
#ifdef DEBUG
    printf("A\n");
#endif
#if DEBUG
    printf("B\n");
#endif

Which of the following is the output when the code above is written inside the main function and executed?

  1. AOnly A is printed
  2. BNothing is printed
  3. 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.
Practice this topic Back to topic

Books on C Programming Basics Ad

As an Amazon Associate I earn from qualifying purchases.

More C Programming Basics questions

  1. A microcontroller output register is declared and used as above. Which of the following correctly describes this declaration?
  2. Which of the following describes undefined behavior as defined by the C standard?
  3. int and unsigned int are 32 bits. Which of the following is undefined behavior according to the C standard?
  4. When the function above is compiled with gcc with optimization enabled, the check if (p == NULL) may be removed. Which of the following is the reason?
  5. Which of the following is what the C standard specifies about the size of the int type?