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

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.


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.


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.

Tags:

C

If Statement