printf() problem

Blair P. Houghton bph at buengc.BU.EDU
Wed Apr 26 23:53:46 AEST 1989


In article <11657 at hodge.UUCP> jdm at hodge.UUCP (jdm) writes:
>
>    Perhaps someone could explain this printf() phenomena to me.
[...wherein printf scrambles the variable-arguments to produce an
unintended ordering of the numbers on the printout...]

Oh, Dr. Torek?  Isn't there an automated version of this answer in
the comp.lang.c.chestnuts archive?

The reason that printf scrambles arguments after the format statement
is that there is no requirement anywhere detailing the order of evaluation
of the arguments to a function.  Apparently, in this instance, since the
arguments were evaluated in reverse order, the passing of arguments
in your C must be done with a LIFO stack, hence the last argument passed
is the first one evaluated, and so on.

[...second-try at debugging:]
>        a = getc(fp);
>        b = getc(fp);
>        c = getc(fp);
>        d = getc(fp);
>
>        printf("%x %x %x %x\n", a, b, c, d);

Ah, now the arguments aren't functions being evaluated, they're just
variables being dereferenced.  See, putting 'getc(fp) where you have
d in the printf would mean that that getc() would be evaluated
_before_ the c was dereferenced, then the b, then the a.  Since the
behavior of the particular function does specify how to arrange the
returned values of the argument-evaluation, you get the output as

	a  b  c  (whatever my getc returned)

even though the first one that printf really knew the answer to was
the getc.

If there are compilers that do it the other way (FIFO stack for args),
I don't know about them.  You're best bet, however, is not to trust
the order of evaluation of arguments, regardless.

Common mistake, really.  I found out about it the same way you are.  And,
no, I didn't go back and check all my old code, neither.

				--Blair
				  "...you can only be just so
				   responsible, y'kno?"



More information about the Comp.lang.c mailing list