[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: short circuit & and | in if and while
From: |
John W. Eaton |
Subject: |
Re: short circuit & and | in if and while |
Date: |
Thu, 14 Sep 2017 08:51:42 -0400 |
User-agent: |
Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Thunderbird/52.2.1 |
On 09/14/2017 05:11 AM, Ernst Reissner wrote:
This explains also why the operators | and & in conditions in until
statements are not shortcut,
i.e. implicitly replaced by && and ||: because until does not exist in
matlab.
The short-circuit behavior of | and & inside IF and WHILE conditions is
not identical to the short-circuit behavior of || and &&.
With || and &&, the operands are evaluated and determined whether they
are true or false. In Octave, this means that if an operand is an array
(for example) it is considered to true if all of the elements are
non-zero. In Matlab, I believe it is an error if the operands are not
scalar values.
In the | and & expressions inside an IF or WHILE condition, short
circuiting can only happen if the first argument is a scalar value. It
might seem that these are equivalent, at least in Matlab, but consider
this case:
if (1 | x) ...; end
vs.
cond = 1 | x;
if (cond) ...; end
Are these always equivalent? Unfortunately no, because in the first
case, the operator always short-circuits because the first operand is a
scalar and is true, but in the second case, short-circuiting doesn't
happen and if X is an empty matrix, then cond will also be an empty
matrix and in the IF condition it is considered false.
It seems to me that because of this bizarre behavior, it's best to NEVER
use | or & inside IF or WHILE conditions, and only use them as
element-wise array operators.
Note that using || instead, there is no difference in behavior, so
if (1 || x) ...; end
and
cond = 1 || x;
if (cond) ...; end
should always do the same thing, regardless of the value of X.
jwe