Skip to main content
Logo image

Section 16.3 Conditional Compilation

printf() statements are a quick and easy way to trace the path of execution of a program.
But...
It can be tedious to insert and delete printf statements when code is being debugged. (After all, we don’t want debug statements flashing by all the time.)
Of course you can comment out (/* */) the printf() statements after code is debugged. But it can still be a bit tedious (yet, it’s my preferred method...).
There is another way however:
You can conditionally include debugging lines (such as printf() statements) by instructing the preprocessor to either include them or to not do so. Any line that starts with a hash mark (#) is meant for and interpreted by the preprocessor. In fact, we have already seen the preprocessor at work with our #include statements! Therefore, when using preprocessor directives to conditionally include debug statements then it is the preprocessor that does the work!

If you cannot see this codecast, please click here.

 
  • #if (condition)
  • #ifdef or #if defined
  • #elif (condition)
  • #else (branch statement for preprocessor!)
  • #endif

Check Your Understanding Check Your Understanding

1.

    What is the output of the following code, once it has been compiled and run:
    #define DEBUG
    . . . 
    #ifdef DEBUG printf("No idea what's wrong.");
    #else printf("All good!");
    #endif
    
  • No idea what’s wrong.
  • Correct
  • No idea what’s wrong. All good!
  • Not quite. Try again!
  • All good!
  • Not quite. Try again!
You could even be fancier and allow for different levels of debugging:

If you cannot see this codecast, please click here.

Check Your Understanding Check Your Understanding

1.

    What is the output of the following code?
    #define DEBUG 1
    #include <stdio.h>
    int main(void)
    {
      int N, i, sum;
      i = 1;
      #if (DEBUG >=2)
        printf("It's a beautiful day! ");
      #elif (DEBUG >=1)
        printf("It's sunny! ");
      #elif (DEBUG >=0)
        printf("Not too bad! ");
      #else
        printf("Huh...! ");
      #endif
    }
    
  • It’s sunny!
  • Correct
  • Huh...!
  • Not quite. Try again!
  • Not too bad!
  • Not quite. Try again!
  • It’s sunny! Not too bad!
  • Not quite. Try again!
  • It’s a beautiful day!
  • Not quite. Try again!
  • It’s a beautiful day! It’s sunny!
  • Not quite. Try again!
  • Not too bad! huh...!
  • Not quite. Try again!

2.

Please correct the following loop, which is supposed to add up the numbers from 1 to n:

admin.....open in new window

When your program performs correctly you’ll be given a keyword to enter in Canvas.

3.

Please correct the following loop, which is supposed to add up the numbers from 1 to n:

admin.....open in new window

When your program performs correctly you’ll be given a keyword to enter in Canvas.