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
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 ...
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With