printf() problem

Mark A Terribile mat at mole-end.UUCP
Fri Apr 28 18:28:42 AEST 1989


In article <11657 at hodge.UUCP>, jdm at hodge.UUCP (jdm) writes:
> 
>     Perhaps someone could explain this printf() phenomena to me.
 
>         printf("%x %x %x %x\n", getc(fp), getc(fp), getc(fp), getc(fp));
> 
>     Although the order of the data in the file is:
>         92 AB 4E 33
>     printf() displays it as:
>         33 4E AB 92
>     Just the reverse of its order in the file.

The compiler wrote code which evaluated the arguments to printf() in
reverse order.

There is no guarantee of in what order the parameters to printf() will be
evaluated, but there is a rationale that let's you guess pretty well
what the compiler will do.

Y'see, it's pretty much required that when printf() is invoked, it see
its arguments as a (non-homogeneous) array, with arg N+1 at an address
higher than arg N.  This may now be a requirement of ANSI C; I don't
know.  Certainly it makes it more nearly possible to write a GOOD varargs
package.

On ``most machines'' or ``many machines'' and probably ``the machine on which
you work'' the stack grows downward; the N+1th object pushed is at an address
lower than the Nth object.  In order to get then N+1th arg at a higher address
than the Nth, they are evaluated in reverse order.  (Yes, it would be possible
to evaluate them in normal order and reverse them, but what a pain, especially
for objects of differing sizes.)

The lesson is simple: don't depend on the order in which arguments are
evaluated.  Sooner or later, on some machine, it will be wrong.
-- 

(This man's opinions are his own.)
>From mole-end				Mark Terribile



More information about the Comp.lang.c mailing list