Logical Operators: Short-Circuit && ||

Syntax

Description

expr1 && expr2 represents a logical AND operation
that employs short-circuiting
behavior. That is, expr2 is not evaluated
if expr1 is logical 0 (false).
Each expression must evaluate to a scalar logical result.

expr1 || expr2 represents a logical OR operation
that employs short-circuiting
behavior. That is, expr2 is not evaluated
if expr1 is logical 1 (true).
Each expression must evaluate to a scalar logical result.

Change Structure Field Value

Short-circuit expressions are useful in if statements when you want multiple conditions to be true. The conditions can build on one another in such a way that it only makes sense to evaluate the second expression if the first expression is true.

Specify an if statement that executes only when S contains an empty field named 'Format'.

if isfield(S,'Format') && isempty(S.Format)
S.Format = '.png';
end
S

S = struct with fields:
File: 'myGraph'
Format: '.png'

The first condition tests if 'Format' is the name of a field in structure S. The second statement then tests whether the Format field is empty. The truth of the second condition depends on the first. The second condition can never be true if the first condition is not true. Since S has an empty field named 'Format', the body statement executes and assigns S.Format the value '.png'.

More About

Logical Short-Circuiting

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.