&& 和 || 的布尔运算符被称为短路求值
它们连接一系列布尔表达式,仅计算最少的表达式来确定整个链的布尔值
在表达式 a && b 中,只有 a 为 true 时才计算子表达式 b
?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | julia> f(x) = (println(x); true) f (generic function with 1 method) julia> g(x) = (println(x); false) g (generic function with 1 method) julia> f( 1 ) && f( 2 ) 1 2 true julia> f( 1 ) && g( 2 ) 1 2 false julia> g( 1 ) && f( 2 ) 1 false julia> g( 1 ) && g( 2 ) 1 false |
在表达式 a || b 中,只有 a 为 false 时才计算子表达式 b
?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | julia> f(x) = (println(x); true) f (generic function with 1 method) julia> g(x) = (println(x); false) g (generic function with 1 method) julia> f( 1 ) || f( 2 ) 1 true julia> f( 1 ) || g( 2 ) 1 true julia> g( 1 ) || f( 2 ) 1 2 true julia> g( 1 ) || g( 2 ) 1 2 false |
&& 比 || 优先级高
?1 2 | julia> false || true && false false |
&& 和 || 可以用 if 语句来表示
&&
?1 2 3 4 5 6 7 | expression && statement # 可以写成 if 语句 if expression statement end |
expression 从而 statement
||
?1 2 3 4 5 6 7 | expression || statement # 可以写成 if 语句 if !expression statement end |
expression 要不就 statement
&& 和 || 的运算对象也必须是布尔值,即为 true 或 false,不能用 1 和 0 来代替
?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | julia> 1 && true ERROR: TypeError: non - boolean (Int64) used in boolean context Stacktrace: [ 1 ] top - level scope at none: 0 julia> 0 && true ERROR: TypeError: non - boolean (Int64) used in boolean context Stacktrace: [ 1 ] top - level scope at none: 0 julia> 1 || true ERROR: TypeError: non - boolean (Int64) used in boolean context Stacktrace: [ 1 ] top - level scope at none: 0 julia> 0 || true ERROR: TypeError: non - boolean (Int64) used in boolean context Stacktrace: [ 1 ] top - level scope at none: 0 |
短路求值的最后一项可以是任何类型的表达式,它可以被求值并返回
?1 2 3 4 5 6 7 8 9 10 11 | julia> true && (x = 2 ) 2 julia> false && (x = 2 ) false julia> true || (x = 2 ) true julia> false || (x = 2 ) 2 |
非短路求值运算符,可以使用位布尔运算符 & 和 |
& 为与运算,与运算中,两个真才为真,即 a && b,a 和 b 都为真,结果才为真
| 为或运算,或运算中,有一个为真就为真,即 a || b,a 或 b 为真,结果为真;a 和 b 全为真,结果也为真
?1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | julia> true & true true julia> true & false false julia> false & true false julia> false & false false julia> true | true true julia> true | false true julia> false | true true julia> false | false false |