This isn\'t a typical question to solve a specific problem, it\'s rather a brain exercise, but I wonder if anyone has a solution.
In development we often need to disable
I'm not sure I should post this because it's not something I think is 'good code', but I'll admit to having used the following technique as a quick-n-dirty way to be able to quickly switch between two small snippets of code when I'm just checking something out:
// in the following , foo() is active:
/**/ foo(); /*/ bar(); /**/
Now just remove one of the asterisks at the front:
// now bar() is active:
/*/ foo(); /*/ bar(); /**/
Of course, this should never make it past the "just checking things out" phase...
Wrapping the code with #if 0
does the trick but then you still need to edit the code to enable/disable it. That's not much better than just using the comment block.
Note that you can also use a defined preprocessor constant:
#ifdef ENABLE_TESTS
// code that you want to run ONLY during tests
#endif
Now when building the code, you can selectively define/un-define this constant in your build process - IDE/makefile/build script/command-line - without needing to edit the code:
$ gcc -DENABLE_TESTS source.c
I've added this answer to counter-balance all of the early #if 0
answers, but this construct from the accepted answer is the best answer to the specific question: /**/ foo(); /*/ bar(); /**/
. Please use such comment tricks sparingly.
Macro is the way to do this..
#define COMPILE
#ifdef COMPILE
//code to comment begins
cout<<"ha ha ha"<<endl;
//code to comment ends
#endif
To disable the code, just comment out #define compile line
In my code, I like to do this in my main.cpp file:
#define CRAZY_EXPERIMENT
#ifdef TEST
#include "Test.h"
#elif ANOTHER_TEST
#include "AnotherTest.h"
#elif CRAZY_EXPERIMENT
#include "CrazyExperiment.h"
#else
int main(int argc, int * argv[]){
runTheProgramLikeNormal();
}
#endif
The header files you see all contain their own main()
. There is only ever one main() function in the program based on what is defined in the first #define
there. If the statement is omitted entirely, it defaults to the canonical main() function you see written.
This makes it easy to write tests for my program that only focus on one or two components by themselves. And the best part is that the test headers are neatly quarantined from my code, so no test code gets left in (or even linked in) by mistake.
Preprocessor if-else also works
#if 1
// ... enabled if 1
#else
// ... enabled if 0
#endif
Use some preprocessor logic to help you out here:
#if 0
//code goes here
#endif
Enjoy