Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how if condition works with multiple expression

My "if condition" look like below ,

if (expression1 || expression2) {
    // do something
} else {
   // do something
}

My question is, if expression1 get satisfied, then code flow goes to else part or expression2 get checked and then goes to else part.

like image 714
Dax Avatar asked Mar 22 '23 02:03

Dax


1 Answers

In most languages, including Objective C, || and && are short-circuit operators. As soon as no more of the arguments to those operators need to be checked, they are not. So if expression1 is true, the whole expression:

if (expression1 || expression2)

evaluates to true for sure as:

if(true OR X)

is by definition true, and X's value therefore does not need to be checked. This short-circuiting behavior clearly depends on the first variable's value. If we have:

if(false || X)

we will have to check X's value to evaluate the whole expression. Similarly, if we have:

if(true && X)

we need to check X's value before we can decide whether the expression evaluates to true. However, if we have:

if(false && X)

we know that the whole expression will be false anyway, so X does not need to be checked - and in many languages, it won't be.

The above points are true even if X is a compound statement that itself consists of more than one variable. So in:

if (true || (expression2 || expression3))

the (expression2 || expression3) part does not need to be evaluated, as the whole statement will still be true regardless of what expression2 and expression3 evaluate to.

like image 149
Martin Dinov Avatar answered Apr 09 '23 17:04

Martin Dinov