Expression sequencing query

Tom Kelly tom at hcrvx1.UUCP
Fri Sep 26 22:05:43 AEST 1986


In article <3926 at utah-cs.UUCP> donn at utah-cs.UUCP (Donn Seeley) discusses
the example:

	a = ((b=1),b) + ((b=2),b) + ((b=3),b)

showing the partial order induced by the expression evaluation rules
of C language (as defined in K & R) and how various orders of
evaluation of the side effects are compatible with that partial
order.  His conclusion is that the "correct" answer is an integer
between 3 and 9 inclusive.  Various other people have posted the
answers obtained by various compilers.

The ANSI C committee (X3J11) has considered this question at some
length, mostly in the context of being able to write safe macros
that involve side-effects (prototypical example: getchar() + getchar().
Can the evaluation of the ?: operators in the "usual" implementation
of getchar be interleaved?).

The current draft (86-098: 9 July 1986) specifies in section 3.3 Expressions
(p. 31):

	Except as indicated by the syntax, or otherwise specified
	later (for the function-call operator (), the unary plus
	operator, &&, ||, ?: and comma operators), the order
	of evaluation of an expression is unspecified.  The
	implementation may evaluate subexpressions in any order,
	even if the subexpressions produce side effects.  The
	order in which side effects take place is unspecified,
	except that the evaluation of the operands of an
	operator that involves a sequence point shall not be
	interleaved with other evaluations.

Section 3.3.17 Comma Operator (p. 46)

	The left operand of a comma operator is evaluated as a
	void expression; there is a sequence point after its
	evaluation.  Then the right operand is evaluated; the
	result has its type and value.

This has the result (along with the definition of sequence point) of
specifying that the value of "a" will be 6, since once one of the
comma expressions is started, it must be fully evaluated before any
of the others are.  Of course, the resulting value of "b" is still
either 1, 2 or 3.

Tom Kelly  (416) 922-1937
Human Computing Resources Corp.
{utzoo, ihnp4, decvax}!hcr!tom



More information about the Comp.lang.c mailing list