Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!csd4.milw.wisc.edu!lll-winken!uunet!wucs1!wugate!dinorah!art From: art@dinorah.wustl.edu (Arthur B. Smith) Newsgroups: comp.lang.c Subject: Re: printf() problem Summary: Argument evaluation order is unspecified in C Keywords: C printf Message-ID: <717@dinorah.wustl.edu> Date: 28 Apr 89 16:12:11 GMT References: <11657@hodge.UUCP> Organization: Washington University (St. Louis) Lines: 52 In article <11657@hodge.UUCP>, jdm@hodge.UUCP (jdm) writes: > > I have a file with binary data. I want to read four consecutive > bytes from the file and display them with printf(). The data > in in the file in hex is: > > 92 AB 4E 33 > > I fopen() the file in binary mode and used the following line > of code to read and print out the data: > > 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 > In Kernighan and Ritchie, 2nd Edition it states: "The order of evaluation of arguments is unspecified; take note that various compilers differ. However, the arguments and the function designator are completely evaluated, including all side effects, before the function is entered." In particular in cc, vcc and gcc under Ultrix 3.0 on a microvax, and presumably in your compilers (MS5.1 and TurboC) printf happens to evaluate its arguments in reverse order. To verify this, try the program: main ( ) {int x = 0; printf("%d, %d, %d\n", ++x, ++x, ++x); } You will probably get 3, 2, 1 as your output. It is not safe to assume that function arguments are evaluated in any particular order. Normally this is not a problem, but when functions have side-effects (as essentially all i/o functions do), this can cause confusion. This was a good question! -art smith (art@dinorah.wustl.edu, ...!uunet!wucs1!dinorah!art)