The &&
and ||
operators short-circuit: if the operand on the left determines the result of the overall expression, the operand on the right will not even be evaluated.
Therefore, a mathematician would describe them as left-associative, e.g.
a && b && c
⇔ (a && b) && c
, because to a mathematician that means a
and b
are considered first. For pedagogical purposes, though, it might be useful to write a && (b && c)
instead, to emphasize that neither b
nor c
will be evaluated if a
is false.
Parentheses in C only change evaluation order when they override precedence. Both a && (b && c)
and (a && b) && c
will be evaluated as a
first, then b
, then c
. Similarly, the evaluation order of both
a + (b + c)
and (a + b) + c
is unspecified. Contrast a + (b * c)
versus (a + b) * c
, where the compiler is still free to evaluate a
, b
, and c
in any order, but the parentheses determine whether the multiplication or the addition happens first. Also contrast FORTRAN, where in at least some cases parenthesized expressions must be evaluated first.
(a && b) && c
differ froma && (b && c)
with respect to short-circuiting? For example, how would(false && b) && c
differ fromfalse && (b && c)
? Both expressions evaluate neitherb
norc
... – Adiabatica
is false, you are correct. ifb
is false,c
never gets evaluated. Basically, if there is somefalse
to the left of some AND'd conditions, the tests stop with it. – Nomadica
is true, andb
isfalse
,c
doesn't get evaluated, regardless of whether you use(a && b) && c
ora && (b && c)
– Cockerfalse
stops anything further right from being tested/executed. With that in mind, it doesn't matter if you write(a && b) && c
ora && (b && c)
ora && b && c
as they are all equivalent. The only thing that does matter is the order of the operands. – Nomadic