Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!csd4.milw.wisc.edu!dogie.macc.wisc.edu!uwvax!rutgers!att!westmark!mole-end!mat From: mat@mole-end.UUCP (Mark A Terribile) Newsgroups: comp.lang.c Subject: Re: printf() problem Summary: Stacking order ... Keywords: C printf Message-ID: <153@mole-end.UUCP> Date: 28 Apr 89 08:28:42 GMT References: <11657@hodge.UUCP> Organization: mole-end--private system. admin: mole-end!newtnews Lines: 38 In article <11657@hodge.UUCP>, jdm@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