Is there any reason for using if(1 || !Foo())? Is there any reason for using if(1 || !Foo())? c c

Is there any reason for using if(1 || !Foo())?


The two are not the same. The first will never evaluate Foo() because the 1 short-circuits the ||.

Why it's done - probably someone wanted to force entry in the then branch for debugging purposes and left it there. It could also be that this was written before source control, so they didn't want the code to be lost, rather just bypassed for now.


if (1 || !Foo() ) will be always satisfied. !Foo() will not even be reached because of short-circuits evaluation.

This happens when you want to make sure that the code below the if will be executed, but you don't want to remove the real condition in it, probably for debug purposes.

Additional information that might help you:

  • if(a && b) - if a is false, b won't be checked.
  • if(a && b) - if a is true, b will be checked, because if it's false, the expression will be false.
  • if(a || b) - if a is true, b won't be checked, because this is true anyway.
  • if(a || b) - if a is false, b will be checked, because if b is true then it'll be true.

It's highly recommended to have a macro for this purpose, say DEBUG_ON 1, that will make it easier to understand what the programmer means, and not to have magic numbers in the code (Thanks @grigeshchauhan).


1 || condition

is always true, regardless whether the condition is true or not. In this case, the condition is never even being evaluated. The following code:

int c = 5;if (1 || c++){}printf("%d", c);

outputs 5 since c is never incremented, however if you changed 1 to 0, the c++ would be actually called, making the output 6.


A usual practical usage of this is in the situation when you want to test some piece of code that is being invoked when the condition that evaluates to true only seldom is met:

if (1 || condition ) {    // code I want to test}

This way condition will never be evaluated and therefore // code I want to test always invoked. However it is definitely not the same as:

if (condition) { ...

which is a statement where condition will actually be evaluated (and in your case Foo will be called)