Comma Operator

Earle R. Horton earleh at eleazar.dartmouth.edu
Sun Jan 15 08:33:37 AEST 1989


In article <922 at quintus.UUCP> nair at quintus () writes:
>What should this print?
>
>	int x, y;
>	printf("%d %d\n", (x = 1, y = 2), x, y);
>
>Shouldn't it be equivalent to:
>
>	int a, x, y;
>	a = (x = 1, y = 2);
>	printf("%d %d %d\n", a, x, y);
>

K&R, 1978, p. 212:

     "Some difficulties arise only when dubious coding practices are
used.  It is exceedingly unwise to write programs that depend on any
of these properties.
     The order of evaluation of function arguments is not specified
by the language..."

     Unfortunately, most beginning programmers assume it is always
left to right.

>Is there any justification in the first one printing
>	2 1 0

     The only thing you are guaranteed to get from code like the first
example is that the first number printed will be 2.  The second two
output values can be any integer value, including the values which you
think should go there.  The compiler writer is free to evaluate
function parameters left-to-right, right-to-left, or even
middle-one-first if that is a more efficient way to do it.
Earle R. Horton. 23 Fletcher Circle, Hanover, NH 03755--Graduate student.
He who puts his hand to the plow and looks back is not fit for the
kingdom of winners.  In any case, 'BACK' doesn't work.



More information about the Comp.lang.c mailing list