Why use #if 0 for block commenting out?
Comments are comments. They describe the code.
Code that's being excluded from compilation is code, not comments. It will often include comments, that describe the code that isn't being compiled, for the moment.
They are two distinct concepts, and forcing the same syntax strikes me as being a mistake.
I'm editing this because I'm in the middle of a sizeable refactor and I'm making heavy use of this pattern.
As a part of this refactor, I'm removing some widely-used types, and replacing them with another. The result, of course, is that nothing will build.
And I really hate spending days fixing one issue after another in the hope that when I'm done everything will build and all the tests will run.
So my first step is to #ifdef-out all the code that won't compile, and then to [Ignore] all the unit tests that call it. With this done everything builds and all the non-ignored tests pass.
The result is a lot of functions that look like this:
public void MyFunction()
{
#if true
throw new NotImplementedException("JT-123");
#else
// all the existing code that won't compile
#endif
}
Then I unignore the unit tests, one at a time, and then fix the functions, one at a time.
It's going to take me a couple of days to worth through all of it, and all of these #if's will be gone, before I create the pull request to merge this, but I find it helpful, during the process.
#if 0
is used pretty frequently when the removed block contains block-comments
I won't say it's a good practice, but I see it rather often.
The single line flow-control+statement is easy enough to understand, although I personally avoid it (and most of the coding guidelines I've worked under forbid it)
BTW, I'd probably edit the title to be somewhat useful "Why use #if 0 instead of block comments"
If you have the following
#if 0
silly();
if(foo)
bar();
/* baz is a flumuxiation */
baz = fib+3;
#endif
If you naively replace the #if 0
/#endif
with /* */
, that will cause the comment to end right after flumuxiation, causing a syntax error when you hit the */
in the place of the #endif
above..
EDIT: One final note, often the #if 0
syntax is just used while developing, particularly if you have to support multiple versions or dependencies or hardware platforms. It's not unusual for the code to be modified to
#ifdef _COMPILED_WITHOUT_FEATURE_BAZ_
much_code();
#endif
With a centralized header defining (or not) hundreds of those #define constants. It's not the prettiest thing in the world, but every time I've worked on a decent sized project, we've used some combination of runtime switches, compile-time constants (this), compile-time compilation decisions (just use different .cpp's depending on the version), and the occasional template solution. It all depends on the details.
While you're the developer just getting the thing working in the first place, though... #if 0
is pretty common if you're not sure if the old code still has value.