order of evaluation parse date s - (nf)
utzoo!utcsrgv!utcsstat!wagner
utzoo!utcsrgv!utcsstat!wagner
Thu Mar 10 00:20:18 AEST 1983
We seem to be confusing several different things all into one big basket
here. There are several cases when C is allowed to re-arrange things,
and we seem to be lumping some of them together. First off:
1) In a private communication, Dave Martindale told me (I hope he doesnt
mind me quoting him "on the air" that the expression
foo(++i,++i) could pass 3 different sets of parameters to foo; i.e., if
i was zero before we started, foo could get passed
1,2
2,1
or
2,2
and the decision was up to the compiler. The relevant quote here is
"The order of evaluation of arguements [to functions] is undefined by
the language; take note that the various compilers differ".
In talking with others around here, it seems the issue boils down to
whether the increment/decrement operators are indivisible or not. I
suspect that there is room for a fourth option; foo could get passed
1,1 if each subexpression first picked up the current value of i into
a different private register, then each private register was incremented,
then each was stored back into the memory location for i, then the value
was passed to foo. The order of evaluation of arguments is undefined...
but are we guaranteed that all of one is finished before another starts,
or are we open to "race" conditions? This may well become important when
multiprocessors become more popular.
2) Someone in news today said that the sequence
i=4;
i=i++;
would always equal 5; this I believe to be incorrect. The action of i++ is
a) copy the value of i to a safe place
b) increment i
c) the result of the subexpression i++ is the value in the safe place.
Point (c) above implies that the result assigned to i would be 4.
In the case i=++i, i is (almost) trivially 5, since the expression
simplifies to i=i+1, with little chance for confusion.
3) Several people have said that C expressions may be rearranged arbitrarily;
that is not true. There are still rules of precedence and so on.
Subexpressions may be computed in any order, even in the face of side
effects, and the order of operands to binary *, +, &, | and ^ can be
shuffled.
This is all very fascinating, and I have spent several hours going through
K&R to try to sort all this out, but I think anyone who relied on any of
these things, even in a language which claimed to have more rigidly
defined order of evaluation, would be coming up with code which was unreadable
by a human, even if the compiler did promise to sort it out.
Michael Wagner, UTCS
More information about the Comp.lang.c
mailing list