Order of Evaluation

Christopher Gould gould at physics.usc.edu
Sat Nov 18 12:20:16 AEST 1989


	This is a question about the justification for pANS _not_
making a change from K&R-1:

	Why is the order of evaluation of subexpressions undefined?
This applies either for subexpressions of most binary operators, or as
arguments in function calls.  Specifically, in the following example,
it is presently undefined as to whether the loop adds the even elements
of a[] with the odd elements of b[], or vice versa:

		int a[SIZE], b[SIZE], i, j;
		for ( i=0 ; i < SIZE-2 ;    )
			j = a[i++] + b[i++];

Of course, this loop could easily be rewritten to specify which one is
desired by moving the i++ into the loop statement, and giving an offset
to the appropriate array index.  This question is not about style.

	What I am asking is, what would go wrong if a new Standard were
to say, for example, you always evaluate left to right.  Then we would
get a[0] + b[1] + a[2] + ....   Since the order of evaluation has never
been guaranteed, a new Standard establishing an order of evaluation
(whatever choice one might make) could not break any currently working
code.  Furthermore, it would reduce the number of ambiguous statements
legally constructed within the language.  (Whether this is in itself a
"good thing" is perhaps the real issue.)

	Incidentally, the above example is a case where parentheses
cannot be used to force the order of evaluation.
_________________

Christopher M. Gould - Univ of Southern Calif - Dept of Physics   (213)743-8521
Internet: gould at usc.edu    Bitnet: gould at uscvm    UUCP: uunet!usc!physics!gould



More information about the Comp.std.c mailing list