Short circuit operators


#1

is the last line intended behaviour?

julia> false || println("Here")
Here

julia> true || println("Here")
true

julia> false && println("Here")
false

julia> true && println("Here")
Here

julia> true && false || println("Here")
Here

julia> false && true || println("Here")
Here

#2

The expression in parantheses evaluates to false. I think this is intended.


#3

Its documented here: https://docs.julialang.org/en/stable/manual/control-flow/#short-circuit-evaluation

Specifically this:

Both && and || associate to the right, but && has higher precedence than || does.


#4

In many programming languages, including Julia, && has higher precedence than ||.

Other programming languages, like bash, give these operators equal precedence, so the result would be different.

Some style guides recommend using parentheses in expressions involving both && and ||, to help the uncertain reader.


#5

so if && and || are right-associative, then why does the following not print anything, shouldn’t true && println("Here") get evaluated first?

julia> false && true && println("Here")
false

julia> parse("""false && true && println("Here")""")
:(false && (true && println("Here")))

#6

The compiler is very smart.

function f()
    false && true && println("Here")
end
julia> @code_warntype f()
Variables:
  #temp#

Body:
  begin 
      return $(QuoteNode(false))
  end::Bool

#7

right-associative means that :(A && B && C) parses as :(A && (B && C)) (as opposed to :((A && B) && C)). A is evaluated first because these expressions are evaluated left-to-right in Julia, and since it’s false, the whole expression is known to be false and there’s no need to evaluate the rest of it.