How to use #ifndef and #endif to turn on and off debugging code.
For my project, I have used several cout statements inorder to check if the program does what I want. My professor calls them debugging code. Now when my professor runs my code he wants us to have a #ifndef statement before our main() and so that #DEBUG can be turned on and off easily.
Then before the cout statement we should have a statement to check if DEBUG is defined or not.
so if DEBUG is define, cout << " whatever " << endl;
But I don't know the proper syntax to do this ? Can you help me with it.
I have this but it doesn't work
1 2 3 4 5 6 7 8 9
#ifndef DEBUG
#define DEBUG
#end if
int main()
{
int x = 10;
#if DEBUG cout << x << endl;
}
Before I begin, littering your code with cout statements is a lousy way to debug. You should really just learn how to use a debugger. With a debugger you can set breakpoints and walk through your code line by line and see the contents of all variables without having to put 'cout's all over your code or recompiling. It's way easier and just overall better.
So yeah -- just use a debugger and get rid of these debug print statements entirely.
But that said.... to answer your actual question:
1 2 3 4 5 6 7 8 9 10 11
#ifdef SOMESYMBOL
// this code will only execute if SOMESYMBOL was #defined
#endif
// this code will execute regardless
#ifndef SOMESYMBOL
// this code will only execute if SOMESYMBOL was *NOT* #defined
#endif
// this code will execute regardless
So basically anything between #ifdef and #endif pairs are conditionally added to your program.
Therefore:
1 2 3 4 5 6 7 8 9
#define DEBUG // define the DEBUG symbol
int main()
{
int x = 10;
#ifdef DEBUG
cout << x << endl; // <- only do this if DEBUG is defined
#endif
}
Then, to turn off "debug mode", you would simply comment out that #define DEBUG line:
1 2 3 4 5 6 7 8 9
// #define DEBUG // <- commented out, so no longer in DEBUG mode
int main()
{
int x = 10;
#ifdef DEBUG
cout << x << endl; // <- only do this if DEBUG is defined
#endif
}