Suppose you have a bit of code you only want to run during your debugging. You don't want it to run in production mode (i.e. after you submit it for grading). A great example is diagnostic output that you print during troubleshooting. How can you do that without remembering to comment out all that debugging code manually? What if you forget?!
First, set up the preprocessor variable.
#define DEBUG 1
Next, use it to fence off the debugging actions.
#if DEBUG
\\ Do this stuff
#endif
You can also get advanced and do one thing if set, do another thing if not set.
#if DEBUG
\\ Do this stuff if DEBUG is set
#else
\\ Do this stuff if DEBUG isn't set
#endif
Don't forget to turn DEBUG off before you submit! Go to the original #define
line and change the value to zero.
#define DEBUG 0
This gist contains a simple program (main.c
) that demonstrates this, along with a Makefile
to build it. Run it like this:
$ ./main first second third last!
Try setting the DEBUG
variable to see the other type of output. What changed?
Now you know how to set up conditional print statements that you can enable and disable as a group.
skillful