7

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 &&

shinjw
  • 3,329
  • 3
  • 21
  • 42
  • Do you want to know this "for boolean types"? For integral types, the logical or operator is very useful in itself, but then the shortcircuit operation is not an alternative since it doesn't operate on integral types. – Erwin Bolwidt Sep 26 '14 at 02:04
  • See answer here: http://stackoverflow.com/questions/9264897/reason-for-the-exsistance-of-non-short-circuit-logical-operators – Halogen Sep 26 '14 at 02:22

4 Answers4

8

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.

arshajii
  • 127,459
  • 24
  • 238
  • 287
4

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).

KoA
  • 299
  • 2
  • 8
2

According to your question,

if you use "|" operator like "if(x == 1 | x==2)" , both expressions are evaluated and if there is at least one TRUE value then run the body of the if block

if you use "||" operator like "if(x == 1 || x==2)", first expression is evaluated and if it is return TRUE then not going to evaluate second expression and run the body of the if block

if you use "&" operator like "if(x == 1 & x==2)" , both expressions are evaluated and if both expressions are return TRUE value then run the body of the if block

if you use "&&" operator like "if(x == 1 && x==2)", first expression is evaluated and if it is return FALSE then not going to evaluate second expression and DO NOT run the body of the if block

Additionally, "||" and "&&" can be used to save the time of operations of your application

1

I asked Josh Bloch himself this question once and he gave another possible reason, IIRC: performance. The non short circuit version has no branch. If the second operand is very cheap and the first is almost always true it could be faster to avoid the conditional evaluation of the second and just let the processor execute it without waiting.

Sean Owen
  • 66,182
  • 23
  • 141
  • 173