Passing Arguments In C

David Geary dmg at ssc-vax.UUCP
Sat Sep 17 06:44:11 AEST 1988


  I'm trying to get a grasp on what actually goes on under the covers
when passing arguments in C.  Here's how I understand the process, please
feel free to correct me if I'm wrong:

Let's say we have the following:

DoIt(x,y,z)
  int x,y,z;
{
  /* Does something... */
}

main()
{
   int a=2, b=3, c=4;

   DoIt(a,b,c);
}

Simple enough? ;-)  Anyway, here goes...

When main() calls DoIt(), the values of a,b, and c are loaded on
a stack somewhere in memory.  However, as I understand it, the
top of the stack is at a higher address than the bottom.  Here's what
I mean:

1)  Load a on the stack (args are loaded left to right, correct?)

  	ADDRESS		VALUE

	106000		2

2)  Then b is pushed on the stack:

	ADDRESS		VALUE

	105996		2
	106000		3

3)  Then c is pushed on the stack:

	ADDRESS		VALUE

	105992		2
	105996		3
	106000		4

Notice that the stack's "top" is at location 106000.  In other words
the stack grows toward the top of memory.  Also, of course, the ADDRESS
locations were made up off the top of my head. I am also assuming, for
the sake of example, that int's take up 4 bytes in memory. 

Then, I guess, the address of the calling routine is loaded onto the
stack, so that we know where to return when DoIt() is done.  So, 
the stack looks like so when everything is pushed on:

	ADDRESS		VALUE

	105988		Address of main() (assume 4 bytes for ptrs, too)
	105992		2
	105996		3
	106000		4

So, this should be the condition the stack is in when DoIt() takes over.


When DoIt() takes over, it only knows where the stack starts in memory,
and then uses that starting address and offsets to access the x,y, and z
in DoIt().



Am I thinking correctly?  I've never written a compiler, so I am not real
sure about this.  Also, I'm a bit confused about what is left up to the
compiler as far as HOW to implement the passing of variable values.  Does
the compiler HAVE TO do it this way.  Does the compiler have the freedom
to, say, grow the stack towards the end of memory instead of the beginning?
Where is all this kind of stuff spelled out?

I teach an Advanced C class, and am showing my students how to write variadic
functions.  I want to make sure that what I'm telling them is correct, and 
also want to prepared to answer the questions in the above paragraph.  

Any help, questions, comments, etc. are greatly appreciated.

Thanx

-- 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~ David Geary, Boeing Aerospace,               ~ 
~ #define    Seattle     RAIN                  ~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~



More information about the Comp.lang.c mailing list