Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple ways to disable parts of code

Tags:

c++

c

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 or switch some parts of code to check different approaches. To do this we use comments or #defines, but my favorite is:

//* [code here] //*/ 

Now when you remove just the first slash the code will become commented-out.

The question: is there any way to implement similar if-else code switch? I tried to find it but I always had some problem and couldn't find a working solution.

And maybe do you know any similar tricks?

like image 705
kolenda Avatar asked Jul 30 '12 17:07

kolenda


1 Answers

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.

like image 195
pb2q Avatar answered Oct 11 '22 15:10

pb2q