As part of the debugging process, we want to isolate the troublesome section of code. We can do this by sprinkling std::cerr statements to validate that certain parts of the code are working. However, after you’re finished with them you need to not only remove them but remember to remove them.
We can do better.
Conditionalizing your code via directives
This tactic resolves the pain of removing and adding std::cerr debugging statements.
We can toggle all the std::cerr comments by manipulating the first #define directive.
To do this, we wrap each std::cerr with a #ifdef, #endif block.
#include <iostream>
#define ENABLE_DEBUG // comment out to disable debugging
int getUserInput()
{
#ifdef ENABLE_DEBUG
std::cerr << "getUserInput() called\\n"; // 2nd debug statement
#endif
std::cout << "Enter a number: ";
int x{};
std::cin >> x;
return x;
}
int main()
{
#ifdef ENABLE_DEBUG
std::cerr << "main() called\\n"; // 1st debug statement
#endif
int x{ getUserInput() };
std::cout << "You entered: " << x << '\\n';
}
That’s it.
Ultimately…
The preprocessor isn’t just for #include statements. It’s a tool you can add to your debugging toolkit.