Skip to content

Commit

Permalink
clarify short-circuit && and || docs (#56420)
Browse files Browse the repository at this point in the history
This clarifies the docs to explain that `a && b` is equivalent to `a ? b
: false` and that `a || b` is equivalent to `a ? true : b`.

In particular, this explains why the second argument does not need to be
a boolean value, which is a common point of confusion. (See e.g. [this
discourse
thread](https://discourse.julialang.org/t/internals-of-assignment-when-doing-short-circuit-evaluation/122178/2?u=stevengj).)
  • Loading branch information
stevengj authored Nov 3, 2024
1 parent 9a77240 commit 0249feb
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions base/docs/basedocs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1305,6 +1305,12 @@ kw";"
Short-circuiting boolean AND.
This is equivalent to `x ? y : false`: it returns `false` if `x` is `false` and the result of evaluating `y` if `x` is `true`.
Note that if `y` is an expression, it is only evaluated when `x` is `true`, which is called "short-circuiting" behavior.
Also, `y` does not need to have a boolean value. This means that `(condition) && (statement)` can be used as shorthand for
`if condition; statement; end` for an arbitrary `statement`.
See also [`&`](@ref), the ternary operator `? :`, and the manual section on [control flow](@ref man-conditional-evaluation).
# Examples
Expand All @@ -1316,6 +1322,9 @@ true
julia> x < 0 && error("expected positive x")
false
julia> x > 0 && "not a boolean"
"not a boolean"
```
"""
kw"&&"
Expand All @@ -1325,6 +1334,12 @@ kw"&&"
Short-circuiting boolean OR.
This is equivalent to `x ? true : y`: it returns `true` if `x` is `true` and the result of evaluating `y` if `x` is `false`.
Note that if `y` is an expression, it is only evaluated when `x` is `false`, which is called "short-circuiting" behavior.
Also, `y` does not need to have a boolean value. This means that `(condition) || (statement)` can be used as shorthand for
`if !(condition); statement; end` for an arbitrary `statement`.
See also: [`|`](@ref), [`xor`](@ref), [`&&`](@ref).
# Examples
Expand All @@ -1334,6 +1349,9 @@ true
julia> false || true || println("neither is true!")
true
julia> pi < 3 || "not a boolean"
"not a boolean"
```
"""
kw"||"
Expand Down

0 comments on commit 0249feb

Please sign in to comment.