Pieter Droogendijk said:
The && operator has a higher precedence than ||. Therefore, a && b is
evaluated first. That makes that
a && b || c
is evaluated as
(a && b) || c
And note: unlike what is true for most other operators, these operands
are evaluated in order, left to right, and when the outcome can be
determined from the operands that have already been evaluated, the
others won't be. For example, in
a*b - c
the order of evaluation could be: first c, then b, then a, then the
multiplication, then the subtraction. Another could be: first b, then a,
then the multiplication, then c, then the subtraction. The only things
you know about the order is that, obviously, the operands must be
evaluated before their operations are performed; and the multiplication
will happen before the subtraction. However, in
a && b || c
the order _must_ be:
evaluate a
if a, then
evaluate b
do logical and
else
result of logical and is guaranteed to be 0
b is not evaluated
if result of and is 0
evaluate c
do logical or
else
logical or is guaranteed to result in 1
c is not evaluated
It is also the case that, while a || b && c has the _value_ of a || (b
&& c), the operands are still evaluated in left-to-right order; that is,
if a is non-zero, the whole of the expression is true, and neither b nor
c need or will be evaluated.
This is a useful feature, because you can do things like
if (ptr!=NULL && *ptr<MAX_VALUE)
without worrying that *ptr might be evaluated before you've checked that
ptr is not null.
Richard