Topic: precedence with || and ()
Author: clamage@eng.sun.com (Steve Clamage)
Date: 1998/01/14 Raw View
In article f3j@panix.com, dragon@panix.com (Michael G Hart) writes:
>
>On several compilers that I have tried the following:
>
>bool foo(), boo();
>.....
>X = foo()== true || (boo() == true);
>....
>
>If foo() test true the experssion in parantheses never gets evaluated.
>
>This to me does not seem correct simply because parantheses have a higher
>precedence that ||
In your example, since == has higher precedence than ||, the
parentheses have no effect -- the meaning of the expression is
the same with and without the parentheses.
Even if that were not the case, there is a special rule for the ||
and && operators: The left operand is always evaluated first; if the
value of that operand is enough to determine the value of the expression,
the right operand is not evaluated at all. (This is usually called
"short-circuit evaluation".) In your example, if foo() is true,
the value of the or-expression is true, and the right operand
is not evaluated at all: in particular, function boo is not called.
(That rule has always been part of C and C++.)
Beyond that, precedence provides only a partial ordering in any case.
The order of evaluation of subexpressions is in general unspecified,
except for special cases like the above, and where a one partial
result is needed to compute another result. Example:
f() * ( g() + h() )
The result of (g()+h()) is needed before the multiply can be
performed, so the + must be performed before the *. But that is
all that we know. The order in which funcitons f, g, and h are
called is unspecified. Function f might be called before both
of g and h, after both, or before one and after the other.
---
Steve Clamage, stephen.clamage@sun.com
---
[ comp.std.c++ is moderated. To submit articles: try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ FAQ: http://reality.sgi.com/employees/austern_mti/std-c++/faq.html ]
[ Policy: http://reality.sgi.com/employees/austern_mti/std-c++/policy.html ]
[ Comments? mailto:std-c++-request@ncar.ucar.edu ]