If condition with multiple OR clauses

224 Views Asked by At

Let us say I have an if condition which checks for one of the events a, b, c,... to be true as shown:

if(a || b || c || .... || z)
    do something

My question is that let us say that the condition c turns out to be true. Then will the program evaluate the conditions d to z or will it proceed to execute the "do something" instructions?

3

There are 3 best solutions below

0
On

Using || will evaluate each condition left to right until it hits a value that's true. It will then stop the check.

if(a || b || c || .... || z)

If you use |, then every condition will be evaluated regardless of the result.

if(a | b | c | .... | z)
0
On

Let's say we have int a = b = c = 1.
If I do ++a || ++b;, a will be 2 after the statement, as an OR-clause only needs one of the condition needs to be true and b will remain 1, as the compiler doesn't continue to check it, as the expression is true already.
If we have --a || ++b however, a evaluates to 0, which will be false in terms of logic. So it continues to check the other condition: b will be 2, which is logically true.
So what do you need to remember?

  • the compiler evaluates those conditions from left to right
  • if one of the OR conditions is true, the compiler doesn't even continue to evaluate the other condition, is it will be true no matter if the other condition is true or false
  • AND conditions need both conditions to be true, so if the first conditions is false, the whole expression is guaranteed to be false, so the compiler doesn't continue to evaluate the other condition. If the first one is true however, the compiler has to check if the other condition is true aswell.

All this is called

short circuit evaluation

For more, click here.

0
On

This is called short circuit evaluation. For example java checks it from left to right; means if c is true it will not check rest of the portion.

But this is not true for all languages. For example csh performs short circuit evaluation from right to left.