Internals of assignment when doing short circuit evaluation

a && b is equivalent to a ? b : false: if a is true it returns the value of b regardless of whether b is boolean, and if a is false it returns false.

So, true && (n=2) is equivalent to n=2 (which returns the right-hand side, 2).

Of course, this will lead to an error if you try to use the result of the && as a boolean value:

julia> if true && (n=2)
          println("Huh?")
       end
ERROR: TypeError: non-boolean (Int64) used in boolean context

The documentation for && should really be clarified on this point: clarify short-circuit && and || docs by stevengj · Pull Request #56420 · JuliaLang/julia · GitHub

2 Likes