Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there good uses for non-short-circuiting logical (boolean) operators in Java/Scala?

Tags:

java

scala

I recently discovered that Java (and Scala) include non-short-circuiting logical operators &, |, and ^. I previously thought these only worked as bitwise operators. While maybe there is an argument for ^, I can't think of very good reasons for using non-short-circuiting logical operators--although sure, I can contrive an example.

Are these operators useful? They seem more likely to cause hard-to-catch bugs.

scala> def foo = {
     |   println("foo")
     |   true
     | }
foo: Boolean

scala> def bar = {
     |   println("bar")
     |   true
     | }
bar: Boolean

scala> foo || bar
foo
res5: Boolean = true

scala> foo | bar
foo
bar
res6: Boolean = true
like image 366
schmmd Avatar asked Mar 02 '12 21:03

schmmd


People also ask

Why short-circuit boolean evaluation is useful?

Short-circuit evaluation, minimal evaluation, or McCarthy evaluation (after John McCarthy) is the semantics of some Boolean operators in some programming languages in which the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression: when the first ...

Which operator is a non short-circuiting logical?

The | and & logical operators, known as non-short circuit operators, should not be used. Using a non-short circuit operator reduces the efficiency of the program, is potentially confusing and can even lead to the program crashing if the first operand acts as a safety check for the second.

Does Java use short-circuiting?

Java's && and || operators use short circuit evaluation. Java's & and | operators also test for the "and" and "or" conditions, but these & and | operators don't do short circuit evaluation.

What does short-circuiting mean in boolean logic?

By short-circuiting, we mean the stoppage of execution of boolean operation if the truth value of expression has been determined already. The evaluation of expression takes place from left to right. In python, short-circuiting is supported by various boolean operators and functions.


2 Answers

They're useful if the right-hand side is a function with side-effects that you want to execute regardless (e.g. logging). However, I would suggest that that's a bit of a code smell and will certainly be unintuitive to the next guy.

like image 61
dty Avatar answered Sep 28 '22 13:09

dty


Hmm. I know they can be incredibly useful for optimizing C/C++ code if used carefully. It might apply to Java as well.

The major use in C -- other than actual bit operations -- is to remove a pipeline stall. The short circuit operators require a branch operation. The bitwise operator will compute both sides and removes the chance for a mispredicted branch and the resulting stall.

like image 23
Zan Lynx Avatar answered Sep 28 '22 13:09

Zan Lynx