Ne v kontakte Asocial programmer's blog

Comment branching in C++

Feature image

Recently I’ve stumbled upon a code snippet in my C++ code, which I’d call “comment branching”. For example, you are experimenting with two implementations of the same functionality represented by a relatively small pieces of code and you need to switch between them back and forth until you decide which one will end up in final version.

Consider following snippet:

1
2
3
4
5
6
long number = 1024;
//*
std::string number_str = std::to_string(number);
/*/
std::string number_str = boost::lexical_cast<std::string>(number);
/**/

If you simply remove first slash from the second line, it turns into this:

1
2
3
4
5
6
long number = 1024;
/*
std::string number_str = std::to_string(number);
/*/
std::string number_str = boost::lexical_cast<std::string>(number);
/**/

Your first implementation became switched off, while code remained completely valid.

It’s pretty obvious, what’s going on there. //* is “commented-out” beginning of multi-line comment which becomes uncommented in second case. If might be considered as a kind in if equivalent. /*/ is a universal token which either starts or ends multi-line comment, depending on preceding context, something like else. Finally, /**/ works as endif token, which terminates comment is case was opened before, or does nothing otherwise. It might also be //*/, but visually I like /**/ more.

Be warned!

This technique has some disadvantages, which must be taken into account:

  • It’s a very obscure way of code management for anyone except you and even for you few months later. Don’t commit this ever, it’s just a time-saver during playing with code.
  • If code block a large, it’s hard to find these boundaries visually, especially taking into account that they most likely won’t be indented.
  • It doesn’t work at all if code between this special comments contains multi-line comments.