What is the purpose of an 'if (0)' block in if-else block?

My question is about the line I have mentioned in the subject and which I can see in many places inside the production code.

The overall code looks like this:

if (0) {
    // Empty braces
} else if (some_fn_call()) {
    // actual code
} else if (some_other_fn_call()) {
    // another actual code
    ...
} else {
    // default case
}

The other branches are irrelevant to my question. I'm wondering what the meaning of putting if (0) here is. The braces are empty, so I don't think that it is supposed to comment some block of code. Does it force the compiler to make some optimization or are its intentions different?

I have tried to search for this explicit case here on SO and on the internet, but with no success. There're similar questions about JavaScript, but not C. There's another question, What happens when a zero is assigned in an `if` condition?, but it discusses zero assignment to a variable, not the 'if (0)' usage itself.


This can be useful if there are #if statements, ala

   if (0)
   {
       // Empty block
   }
#if TEST1_ENABLED
   else if (test1())
   {
      action1();
   }
#endif
#if TEST2_ENABLED
   else if (test2())
   {
      action2();
   }
#endif

etc.

In this case, any (and all) of the tests can be #if'ed out, and the code will compile correctly. Almost all compilers will remove the if (0) {} part. A simple autogenerator could generate code like this, as it is slightly easier to code - it doesn't have to consider the first enabled block separately.


I sometimes use this for symmetry so I can move the other else if{ freely around with my editor without having to mind the first if.

Semantically the

if (0) {
    // Empty braces
} else 

part doesn't do anything and you can count on optimizers to delete it.


I've seen a similar pattern used in generated code. For example, in SQL, I've seen libraries emit the following where clause.

where 1 = 1

This presumably makes it easier to just add on other criteria, because all additional criteria can be prepended with and instead of an additional check to see if it is the first criteria or not.


As written, the if (0) {} clause compiles out to nothing.

I suspect the function of the clause at the top of this ladder is to provide an easy place to temporarily disable all the other functionality at once (for debugging or comparison purposes) by changing the 0 to a 1 or true.


I am not sure of any optimizations, but my two cents:

This happened because of some code modification, where one primary condition was removed, (the function call in initial if block, let's say), but the developers/ maintainers

  • were lazy to restructure the if-else block
  • did not want to go down on the branch coverage count

so instead of removing the associated if block, they simply changed the condition to if(0) and moved on.