GNU Octave Manual Version 3by John W. Eaton, David Bateman, Søren Hauberg Paperback (6"x9"), 568 pages ISBN 095461206X RRP £24.95 ($39.95) |

### 8.5.2 Short-circuit Boolean Operators

Combined with the implicit conversion to scalar values in `if`

and
`while`

conditions, Octave's element-by-element boolean operators
are often sufficient for performing most logical operations. However,
it is sometimes desirable to stop evaluating a boolean expression as
soon as the overall truth value can be determined. Octave's
*short-circuit* boolean operators work this way.

`boolean1`&&`boolean2`-
The expression
`boolean1`is evaluated and converted to a scalar using the equivalent of the operation`all (`

. If it is false, the result of the overall expression is 0. If it is true, the expression`boolean1`(:))`boolean2`is evaluated and converted to a scalar using the equivalent of the operation`all (`

. If it is true, the result of the overall expression is 1. Otherwise, the result of the overall expression is 0.`boolean1`(:))**Warning:**there is one exception to the rule of evaluating`all (`

, which is when`boolean1`(:))`boolean1`

is the empty matrix. The truth value of an empty matrix is always`false`

so`[] && true`

evaluates to`false`

even though`all ([])`

is`true`

. `boolean1`||`boolean2`-
The expression
`boolean1`is evaluated and converted to a scalar using the equivalent of the operation`all (`

. If it is true, the result of the overall expression is 1. If it is false, the expression`boolean1`(:))`boolean2`is evaluated and converted to a scalar using the equivalent of the operation`all (`

. If it is true, the result of the overall expression is 1. Otherwise, the result of the overall expression is 0.`boolean1`(:))**Warning:**the truth value of an empty matrix is always`false`

, see the previous list item for details.

The fact that both operands may not be evaluated before determining the overall truth value of the expression can be important. For example, in the expression

a && b++

the value of the variable `b` is only incremented if the variable
`a` is nonzero.

This can be used to write somewhat more concise code. For example, it is possible write

function f (a, b, c) if (nargin > 2 && isstr (c)) ...

instead of having to use two `if`

statements to avoid attempting to
evaluate an argument that doesn't exist. For example, without the
short-circuit feature, it would be necessary to write

function f (a, b, c) if (nargin > 2) if (isstr (c)) ...

Writing

function f (a, b, c) if (nargin > 2 & isstr (c)) ...

would result in an error if `f`

were called with one or two
arguments because Octave would be forced to try to evaluate both of the
operands for the operator `‘&’`.

ISBN 095461206X | GNU Octave Manual Version 3 | See the print edition |