Comment branching in C++
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:
If you simply remove first slash from the second line, it turns into this:
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
/*/ is a universal token which either starts or ends multi-line comment, depending on preceding context, something like
/**/ works as
endif token, which terminates comment is case was opened before, or does nothing otherwise. It might also be
//*/, but visually I like
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.