Skip to content

Commit 0249feb

Browse files
authored
clarify short-circuit && and || docs (JuliaLang#56420)
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).)
1 parent 9a77240 commit 0249feb

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

base/docs/basedocs.jl

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1305,6 +1305,12 @@ kw";"
13051305
13061306
Short-circuiting boolean AND.
13071307
1308+
This is equivalent to `x ? y : false`: it returns `false` if `x` is `false` and the result of evaluating `y` if `x` is `true`.
1309+
Note that if `y` is an expression, it is only evaluated when `x` is `true`, which is called "short-circuiting" behavior.
1310+
1311+
Also, `y` does not need to have a boolean value. This means that `(condition) && (statement)` can be used as shorthand for
1312+
`if condition; statement; end` for an arbitrary `statement`.
1313+
13081314
See also [`&`](@ref), the ternary operator `? :`, and the manual section on [control flow](@ref man-conditional-evaluation).
13091315
13101316
# Examples
@@ -1316,6 +1322,9 @@ true
13161322
13171323
julia> x < 0 && error("expected positive x")
13181324
false
1325+
1326+
julia> x > 0 && "not a boolean"
1327+
"not a boolean"
13191328
```
13201329
"""
13211330
kw"&&"
@@ -1325,6 +1334,12 @@ kw"&&"
13251334
13261335
Short-circuiting boolean OR.
13271336
1337+
This is equivalent to `x ? true : y`: it returns `true` if `x` is `true` and the result of evaluating `y` if `x` is `false`.
1338+
Note that if `y` is an expression, it is only evaluated when `x` is `false`, which is called "short-circuiting" behavior.
1339+
1340+
Also, `y` does not need to have a boolean value. This means that `(condition) || (statement)` can be used as shorthand for
1341+
`if !(condition); statement; end` for an arbitrary `statement`.
1342+
13281343
See also: [`|`](@ref), [`xor`](@ref), [`&&`](@ref).
13291344
13301345
# Examples
@@ -1334,6 +1349,9 @@ true
13341349
13351350
julia> false || true || println("neither is true!")
13361351
true
1352+
1353+
julia> pi < 3 || "not a boolean"
1354+
"not a boolean"
13371355
```
13381356
"""
13391357
kw"||"

0 commit comments

Comments
 (0)