Short-Circuit ||

Short-circuit logical OR: the second operand is evaluated only if needed.

Category: Language Fundamentals > Operators and Elementary Operations

Syntax

tf = a || b

Returns true if a or b is true. b is not evaluated when a is true.

Description

Evaluation stops at the first true operand. A common pattern is a cheap test first and an expensive or risky one second: isempty(x) || x(1) == 0 is safe on an empty x, since the indexing is skipped.

|| is meant for if and while conditions with scalar results. Use | for element-wise OR of arrays.

Input arguments

a, b
Expressions that evaluate to logical scalars (or arrays treated as true only if all elements are nonzero).

Output arguments

tf
Logical scalar.

Example

x = [];
isempty(x) || x(1) == 0
x = [0 1];
isempty(x) || x(1) == 0
x = 7;
x < 0 || x > 5
Output
ans = logical
   1
ans = logical
   1
ans = logical
   1

See also

| any