Increment Operators vs. Precedence
Will Crowder
willcr at bud.sos.ivy.isc.com
Fri Mar 8 03:46:26 AEST 1991
In article <668294528.3716 at mindcraft.com>, fred at mindcraft.com (Fred Zlotnick)
writes:
|> A related example is the conditional expression
|> x++ && y++ || z++
|> The precedence rules state that this means
|> ((x++) && (y++)) || (z++)
|> As it happens, there is an order of evaluation rule for && and ||, and it
|> causes strange results here: x is always incremented, y is incremented
|> if x was not -1, and z is incremented only if x and y were both -1. Thus
|> even though ++ is the highest precedence operator in this expression, not
|> all ++'s get evaluated. Note that for most C operators (anything except &&,
|> ||, ?: and comma) there is no specified order of evaluation.
Actually, x is always incremented, y is incremented if x wasn't 0 (not -1)
and z is incremented if either x or y is 0.
Remember, the value of the expression (x++) is x *before* the increment, not
after. Since all increment operators in this expression are postincrement,
the incremented values of x, y and z do not come into play in determining
which parts of the expression are evaluated.
Due to C's (rather handy) shortcircuiting of && and || operators, the right
side of the || is only evaluated if the left side is false. For &&, the
right side is only evaluated if the left side is true. Since the left side
of the || expression in this case is the && expression, the && expression
must be false (either x or y 0) for the right side to be evaluated.
Hope this helps,
Will
|> Hope this helps.
|> Fred Zlotnick | #include <std.disclaimer>
|> fred at mindcraft.com | #include <brilliant.quote>
|> ...!{decwrl,ames,hpda}!mindcrf!fred |
More information about the Comp.lang.c
mailing list