variable number of strings passed to function - how?

Nick Holloway alfie at warwick.UUCP
Wed Oct 26 19:55:40 AEST 1988


In article <3533 at ihuxz.ATT.COM> burris at ihuxz.ATT.COM (Burris) writes:
>In the C language arguments are placed on the stack in reverse order
>
Demonstration 1:
    main () { int i = 1; printf ( "%d %d %d\n", i++, i++, i++ ); }

Note: I _do_ know that this is bad code - but it does demonstrate the
      order of evaluation.

First I compiled and ran this on a sun3. The output is what most people 
expect from their compiler. (args evaluated from right to left)
    3 2 1
Then I compiled it on the sun4 here (sparc), and the results suprised me!
    2 1 3
Looking at the assembly, it was confusing, but it did seem rather long, 
so I compiled with -O, and this gave
    1 2 3

I think this is a good demonstration of why you must never depend on 
the order evaluation of arguments (On the sparc, even compile time 
flags make a difference). 

Demonstration 2:
    test (a,b) int a,b; 
	{ printf ( "&a=%u\n&b=%u\n", (unsigned)&a, (unsigned)&b ); }
    main () { test ( 1, 2 );}

On the sun3, the output was: (args at increasing addresses)
    &a=251657624
    &b=251657628
On the sun4: (args at decreasing addresses)
    &a=4160748428
    &b=4160748432

So we have concrete examples why you can never assume anything about the
calling convention if you wish your programs to be portable, and use a 
standard interface such as <varargs.h>/<stdargs.h>.

Note: I normally indent my programs, this is just to cut down on space in 
      this article. Also I did include <stdio.h>.
--
JANET : alfie at uk.ac.warwick.cs        | `O O' |16 Queens Rd|   /: :   :-- : :--
UUCP  : ..!mcvax!ukc!warwick!alfie    |// ^ \\|Hertford    |  / : :   :   : :
BITNET: alfie%uk.ac.warwick.cs at ukacrl --------|Herts       | /--: :   :-  : :-
ARPA  : alfie%cs.warwick.ac.uk at cunyvm.cuny.edu|England     |/   : :__ :   : :__



More information about the Comp.lang.c mailing list