Main Content

Short-Circuit OR, ||

Logical OR with short-circuiting



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


collapse all

Create two vectors.

X = [1 0 0 1 1];
Y = [0 0 0 0 0];

Using the short-circuit OR operator with X and Y returns an error. The short-circuit operators operate only with scalar logical conditions.

Use the any and all functions to reduce each vector to a single logical condition.

any(X) || all(Y)
ans = logical

The expression is equivalent to 1 OR 0, so it evaluates to logical 1 (true) after computing only the first condition, any(X).

Input Arguments

collapse all

Logical expressions, specified as any valid MATLAB® expressions that evaluate to logical scalars.

Example: isscalar(x) || isvector(x)

Example: (x > 1) || (x < -1)

Data Types: logical

More About

collapse all

Logical Short-Circuiting

With logical short-circuiting, the evaluation of logical expressions can terminate early once the result becomes fully determined. 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. Used properly, this technique enables you to perform complex comparisons efficiently in your code.

For example, in the expression A && B, MATLAB does not evaluate condition B at all if condition A is false. Once it is determined that A is false, the value of B cannot 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.

    However, you should 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.

Extended Capabilities

Version History

Introduced before R2006a