Subroutine layout in C

Greg Pasquariello X1190 gpasq at picuxa.UUCP
Fri Dec 23 00:24:33 AEST 1988


In article <2800002 at uxg.cso.uiuc.edu> phil at uxg.cso.uiuc.edu writes:
-
-I want to write a subroutine in C, called S.  I want S to be known outside.
-I also want to have two subroutines X and Y to be known ONLY to S (not known
-outside of S).  Either can be called by S, and each calls the other in a
-recursive way.  I also need to share several variables entirely within
-this context (shared between S, X, Y).  They can be static.  There will
-only be 1 instance of S (and therefore also of X and Y, but that should
-be hidden).  Main program M should be able to call S, but any references
-to X and Y will not be resolved by the module S.
-
-How do I lay out the arrangement of source for S?  An example would be
-appreciated.  Thanks.
-
---Phil--

Here's how to do it.  This is in the source file S.c, and assumes that the
routines return ints.  Just change your code accordingly if they don't.  It
also does not show any function parameters, so you will have to customize
your code for that also (obviously).

/*
	This declares your functions and variables as static (i.e. known 
	only within this source module).  See K+R2 A4.1.
*/
static int X();
static int Y();

static int var1;
static int var2;

/*
	This declaration of S() will enable it to be found externally when
	called by any other routine in the program, for example M().  Notice
	that S has access to the both the static variables and the static
	functions X() and Y().
*/
S() 
	{
	var1 = 1;
	X();
	Y();
	...
	}

/*
	Here, your two static functions X() and Y() have access to the 
	variables, as well as each other.
*/
static int X()
	{
	var1 = var2 = 0;
	Y();
	...
	}

static int Y()
	{
	var1 = var2 = 0;
	X();
	...
	}


-- 
=============================================================================
By the time they had diminished from 		  Greg Pasquariello AT&T PMTC
50 to 8, the dwarves began to suspect Hungry.	  att!picuxa!gpasq  
=============================================================================



More information about the Comp.lang.c mailing list