Is there any reason for using if(1 || !Foo())?
Solution 1:
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.
Solution 2:
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)
- ifa
isfalse
,b
won't be checked. -
if(a && b)
- ifa
istrue
,b
will be checked, because if it'sfalse
, the expression will befalse
. -
if(a || b)
- ifa
istrue
,b
won't be checked, because this istrue
anyway. -
if(a || b)
- ifa
isfalse
,b
will be checked, because ifb
istrue
then it'll betrue
.
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).
Solution 3:
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)