Short-Circuit &&

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

Category: Language Fundamentals > Operators and Elementary Operations

Syntax

tf = a && b

Returns true if both a and b are true. b is not evaluated when a is false.

Description

Evaluation goes left to right and stops at the first false operand. This guards expressions that would fail otherwise: k <= numel(x) && x(k) > 0 never indexes beyond the end because the second test is skipped when k is too large.

&& is meant for if and while conditions. For element-wise combination of arrays use &. Precedence: && binds more loosely than |, and || more loosely than &&.

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 = [3 -1 5];
k = 4;
k <= numel(x) && x(k) > 0
k = 2;
k <= numel(x) && x(k) > 0
Output
ans = logical
   0
ans = logical
   0

See also

& any