Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!cornell!uw-beaver!mit-eddie!bu-cs!buengc!bph From: bph@buengc.BU.EDU (Blair P. Houghton) Newsgroups: comp.lang.c Subject: Re: printf() problem Message-ID: <2679@buengc.BU.EDU> Date: 26 Apr 89 13:53:46 GMT References: <11657@hodge.UUCP> Reply-To: bph@buengc.bu.edu (Blair P. Houghton) Followup-To: comp.lang.c Organization: Boston Univ. Col. of Eng. Lines: 46 In article <11657@hodge.UUCP> jdm@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?"