37

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?

3
  • 3
    Using comments will be problematic since comments can't be nested. If you have comments inside the disabled code then that won't work. Commented Jul 30, 2012 at 17:42
  • 1
    Good point Joachim. But when you use it during prototyping you don't use comments so much.
    – kolenda
    Commented Jul 30, 2012 at 17:45
  • 1
    Ah no then, but on the other hand code that was supposed to be just a prototype tends to creep into the actual code way too often in the real world. Commented Jul 30, 2012 at 17:47

14 Answers 14

56

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.

5
  • The name sounds a little confusing. I would expect compiling with -DDISABLE_TEST to disable test code. Here it enables it. Commented Jul 30, 2012 at 17:47
  • @ArjunShankar yes that is confusing
    – pb2q
    Commented Jul 30, 2012 at 17:48
  • 3
    Yes, this is better. And this is a useful answer. +1. Commented Jul 30, 2012 at 17:50
  • 1
    is there anything as neat as this in java? Commented Jul 31, 2012 at 5:31
  • 2
    @LightyearBuzz no preprocessor in java, no. But java does have a similar -D command line switch that allows you to pass System property values on the command line. You'll need to resort to standard runtime if/then tests, e.g.: if (System.getProperty("key", "defaultValue")). The C #if/#endif is compile-time.
    – pb2q
    Commented Jul 31, 2012 at 17:42
37
#if 0
...disabled code here
#endif
1
  • 5
    Using #if 0 for disabled code and #if 01 for enabled allows switching between the two cases by typing a single character (a delete or a 1) rather than two, (a delete and the new value). Commented Jul 30, 2012 at 23:07
26

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...

1
  • 16
    @kolenda: #if 0 with an #else does the same thing, and it's much much cleaner... Commented Jul 30, 2012 at 23:05
14

Preprocessor if-else also works

#if 1
  // ... enabled if 1
#else
  // ... enabled if 0
#endif
0
6

Use some preprocessor logic to help you out here:

#if 0
    //code goes here
#endif

Enjoy

6

Sometimes I use the below trick to switch between two lazy comments.

//* <-- remove the first slash
[code block 1]
/*/
[code block 2]
//*/
0
5

Well, if the code that needed to be disabled once or twice before finalizing, I prefer to use hotkeys provided by IDE to comment that code out, and later comment in. Yes, I need to select the code block first, but I prefer not to include one more debugging variable/preprocessor directive/if statement every time I need to disable a part of code. This happens to be most of the time.

If, on the other hand, I need to repeatedly switch between 2 code blocks to find the right thing, then I use a if (0) / if (1) to disable/enable code block.

[code block 1]

Later

if (0)
{
    [code block 1]
}
else
{
    [code block 2]
}
2
  • 1
    +1 because, with your syntax, the non-executed code is still checked for syntax errors, whereas #ifdef(s) hide that code from the compiler. Commented Aug 11, 2012 at 23:54
  • and it still suffers speed if inside big loop
    – jangorecki
    Commented Jun 7, 2020 at 22:53
3

If you're doing checks at compile time, you can use Gigi's answer, which will conditionally not compile sections of code. Note that the preprocessor has no knowledge of variables, or sizeof, or other things handled by the compiler (so using something like 4 == sizeof(int) will not fly)

If you want to compile in little bits of debugging code that should not ever get run, you can use regular conditional statements, like such

bool debugging = false;

// banana banana banana

if (debugging)
{
    // do a bunch of stuff here
}

You can then use a debugger to access the skipped section by assigning debugging to true.

3

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

1
  • 1
    More explicitly, you could use -DCOMPILE to enable/disable the block at compile-time, and not have to worry about the #define clause at the beginning.
    – Makoto
    Commented Jul 31, 2012 at 21:09
3

Synchronously switching on/off chunks of code scattered across the program is sometimes a need too.

Inspired by this earlier post by Graham I cooked up something like this:

void doNothing(){}
#define DO_IF(flag, code) flag ? code : doNothing();

This can be for instance used as follows:

DO_IF(collectStats, recordStats());
DO_IF(collectStats, store(pullStat()));

An that is even better:

#define DO_IF(flag,code) if( flag ) { code; }
1
  • This solution is far more clean than the most voted one. You saved my day!
    – Moia
    Commented Jan 18, 2018 at 15:15
2
1 ? foo() : bar();

This executes foo(). Change the 1 to a 0 to execute bar() instead.

Unlike the suggestions involving preprocessor directives or comments, both possible branches are compiled, so you get the full benefit of the compiler's syntax checking.

2

Sometimes i use this approach to just not overbloat the code by infinite sequence of if-endif definitions.

debug.hpp

#ifdef _DEBUG
    #define IF_DEBUG(x) if(x)
#else
    #define IF_DEBUG(x) if(false)
#endif

example.cpp

#include "debug.hpp"

int a,b, ... ,z;

...

IF_DEBUG(... regular_expression_here_with_a_b_z ...) {
    // set of asserts
    assert(... a ...);
    assert(... b ...);
    ...
    assert(... z ...);
}

This is not always effective, because compiler may warn you about unused variables has used inside such disabled blocks of code. But at least it is better readable and unused variable warnings can be suppressed for example like this:

IF_DEBUG(... regular_expression_here_with_a_b_z ...) {
    // set of asserts
    assert(... a ...);
    assert(... b ...);
    ...
    assert(... z ...);
}
else {
    (void)a;
    (void)b;
    ....
    (void)z;
}

It is not always a good idea, but at least helps to reorganize the code.

1

the following logic should contain the simplest approach

if(isMode1)
{
    //Code for mode1
}
else
{
    //Code for other modes
}

although I think the correct way is to use PreProcessor Directives

1

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.