Why use #if 0 for block commenting out?

Viewed 44956

Reverse engineering code and I'm kind of appalled at the style, but I wanted to make sure there's no good reason for doing these things....

Is it just me or is this a horrible coding style

if ( pwbuf ) sprintf(username,"%s",pwbuf->pw_name);
else sprintf(username,"%d",user_id);

And why wrap code not intended for compilation in an

#if 0
....
#endif

Instead of comments?


EDIT: So as some explained below, this is due to the possibility to flummox /* */ which I didn't realize.

But I still don't understand, why not just use your programming environment tools or favorite text editor's macro's to block comment it out using "//"

wouldn't this be MUCH more straightforward and easy to know to visually skip?


Am I just inexperienced in C and missing why these things might be a good idea -- or is there no excuse, and I'm justified in feeling irritated at how ugly this code is?

13 Answers

#if is a macro which checks for the condition written aside to it, since ‘0’ represents a false, it means that the block of code written in between ‘#if 0’ and ‘#endif’ will not be compiled and hence can be treated as comments.

So, we can basically say that #if 0 is used to write comments in a program.

Example :

#if 0
int a;
int b;
int c = a + b;
#endif

The section written between “#if 0” and “#endif” are considered as comments.

Questions arises : “/* … */” can be used to write comments in a program then why ”#if 0”?

Answer : It is because, #if 0 can be used for nested comments but nested comments are not supported by “/* … */”

What are nested comments? Nested Comments mean comments under comments and can be used in various cases like :

Let us take an example that you have written a code like below:

enter image description here

Now, someone is reviewing your code and wants to comment this whole piece of code in your program because, he doesn’t feel the need for this piece of code. A common approach to do that will be :

enter image description here

The above is an example of nested comments.The problem with the above code is, as soon as the first “/” after “/” is encountered, the comment ends there. i.e., in the above example, the statement : int d = a-b; is not commented.

This is solved by using “if 0” :

enter image description here

Here, we have used nested comments using #if 0.

I can name a few reasons for using #if 0:

  • comments don't nest, #if direcitves do;

  • It is more convenient: If you want to temporarily enable a disabled block of code, with #if 0 you just have to put 1 instead of 0. With /* */ you have to remove both /* and */;

  • you can put a meaningful macro instead of 0, like ENABLE_FEATURE_FOO;

  • automated formatting tools will format code inside #if block, but ignore commented out code;

  • it is easier to grep for #if than look for comments;

  • it plays nicer with VCS because you aren't touching the original code, just adding lines around it.

Related