Comma Operator

Colin Plumb w-colinp at microsoft.UUCP
Sat Jan 14 19:28:31 AEST 1989


nair at quintus () wrote:
> What should this print?
> 
> 	int x, y;
> 	printf("%d %d\n", (x = 1, y = 2), x, y);

(I assume you really want a third %d in there.)

It should print 2 <garbage> <garbage>.  If a machine evaluates arguments
left-to-right, it would print 2 1 2, but on many machines, arguments are
pushed right-to-left, and evaluated in the same order.  Thus, x and y
get assigned after their old values have been pushed.

C has never made any guarantees about the order in which arguments to
functions are evaluated; while the comma operator does, the comma between
function arguments is a different beast entirely.

> Shouldn't it be equivalent to:
> 
> 	int a, x, y;
> 	a = (x = 1, y = 2);
> 	printf("%d %d %d\n", a, x, y);

Ah, this is different... there's a sequence point at the ; after the
assignment to a, so it is guaranteed that x and y have their new values
before the call is made.

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

Yes.
-- 
	-Colin (uunet!microsof!w-colinp)



More information about the Comp.lang.c mailing list