Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logical operator OR without short circuit [duplicate]

Tags:

java

When would you ever need to use the non short circuit logical operator or? In other words...

When would you use

if(x == 1 | x==2)

Instead of

if(x == 1 || x==2)

If the first conditional is true... Then the entire statement is already true.

Update: and the same question for & and &&

like image 1000
shinjw Avatar asked Sep 26 '14 01:09

shinjw


People also ask

Does || short circuit in C?

The logical AND and logical OR operators ( && and || , respectively) exhibit "short-circuit" operation. That is, the second operand is not evaluated if the result can be deduced solely by evaluating the first operand.

Why are && and || operators called short circuit?

The logical AND expression is a short-circuit operator. As each operand is converted to a boolean, if the result of one conversion is found to be false , the AND operator stops and returns the original value of that falsy operand; it does not evaluate any of the remaining operands.

What are logical operators in short?

A logical operator is a symbol or word used to connect two or more expressions such that the value of the compound expression produced depends only on that of the original expressions and on the meaning of the operator. Common logical operators include AND, OR, and NOT.

Are logical operators evaluated with the short circuit?

Do logical operators in the C language are evaluated with the short circuit? Explanation: None.


2 Answers

One example arises if we have two functions and we want them both to be executed:

if (foo() | bar())

If we had used ||, then bar() will not be executed if foo() returns true, which may not be what we want.

(Although this is somewhat of an obscure case, and more often than not || is the more appropriate choice.)

An analogous situation can come up with &/&&:

if (foo() & bar())

If we had used &&, then bar() will not be executed if foo() returns false, which again may not be what we want.

like image 98
arshajii Avatar answered Sep 25 '22 02:09

arshajii


Well, there are a few reasons. Take the following example:

if(someImportantMethod() | otherImportantMethod())
{
    doSomething();
}

If you needed both methods to be run, regardless of the result of the other method, then you'd have to use | instead of ||.

Something to note is that the short circuit operands are slightly slower (though the performance impact is usually unnoticable).

like image 20
KoA Avatar answered Sep 23 '22 02:09

KoA