printf() problem

Arthur B. Smith art at dinorah.wustl.edu
Sat Apr 29 02:12:11 AEST 1989


In article <11657 at hodge.UUCP>, jdm at 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 at dinorah.wustl.edu, ...!uunet!wucs1!dinorah!art)



More information about the Comp.lang.c mailing list