Mail Archives: djgpp/1997/08/10/19:46:36
Charles Krug wrote:
> > Is it safe to assume that the expression
> >
> > if(first_function()==OK && second_function()==OK &&
> > third_function()==OK) return(OK);
> >
> > will be evaluated from left to right?
>
> No.
>
> I think that ANSI tries to demand left-to-right evalutaion of &&. But
> not all compilers do this correctly. To guarantee left-to-right
> evaluation, you need:
This is just plain wrong.
ANSI C guarantees that && and || are short-circuiting; that is, the
arguments are evaluated in order from left to right, and if an expression
returns a value that determines the value of the logical expression, then
the other arguments will not be evaluated. You really should get a good
book on ANSI C to allay you fears. Short-circuiting of && and || was
present in traditional C, much less K&R C. (In fact, bitwise & and | used
to substitute as logical operators as well -- the && and || operators were
chosen to simplify the logical evaluation _and_ introduce
short-circuiting.)
I have not seen _one_ ANSI C implementation (and I've tried dozens) that
do not do this correctly.
In the expression
if (f() && g() && h()) return 0;
f is called; if it returns zero then the others aren't called. But if it
isn't, then g is called, with the same criteria: if it returns zero, then
h isn't called. If f, g, and h all return nonzero values, then this
fragment returns 0.
This works for other expressions with side effects:
if (i >= 0 && a[i - 1] && j++) /* ... */
Note the implication here; we first check to make sure that i is
nonnegative (that is, a valid array offset), and then with the
short-circuited && expression, index into the array. There's no danger of
this crashing, because if i is negative, the if expression here will stop
evaluating before it gets to the array subscription.
> The professional in me would also like to see comments explaining what
> first(), second(), and third() do, just in case you put this project
> away for a year. This is much easier to accomplish when they are on
> seperate lines.
Not an issue if they are given real names, rather than hypothetical names
given here.
> The best explanation of the rules of precedence I've ever heard:
>
> "Multiply and divide before you add and subtract"
>
> "Put parentheses around everything else"
Then again, people who are too uninterested to learn the rules of
precedence get stomped on the head with a big LAZY.
--
Erik Max Francis, &tSftDotIotE / email / mailto:max AT alcyone DOT com
Alcyone Systems / web / http://www.alcyone.com/max/
San Jose, California, United States / icbm / 37 20 07 N 121 53 38 W
\
"Love is not love which alters / when it alteration finds."
/ William Shakespeare, _Sonnets_, 116
- Raw text -