With logical short-circuiting, the second operand, expr2
,
is evaluated only when the result is not fully determined by the first
operand, expr1
.
Due to the properties of logical AND and OR, the result of a
logical expression is sometimes fully determined before evaluating
all of the conditions. The logical and
operator
returns logical 0
(false
) if
even a single condition in the expression is false. The logical or
operator
returns logical 1
(true
) if
even a single condition in the expression is true. When the evaluation
of a logical expression terminates early by encountering one of these
values, the expression is said to have short-circuited.
For example, in the expression A && B
, MATLAB^{®} does
not evaluate condition B
at all if condition A
is
false. If A
is false, then the value of B
does
not change the outcome of the operation.
When you use the element-wise &
and |
operators
in the context of an if
or while
loop
expression (and only in that context), they use
short-circuiting to evaluate expressions.
Note:
Always use the && and || operators
to enable short-circuit evaluation. Using the & and | operators
for short-circuiting can yield unexpected results when the expressions
do not evaluate to logical scalars. |