Subroutine layout in C
Eric S. Raymond
eric at snark.UUCP
Fri Dec 23 04:06:13 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.
Let xreturn, yreturn and sreturn be the return types of X, Y and S. Then the
simplest way to accomplish this is:
static int sharevar1;
static char *sharevar2;
static xreturn X()
{
yreturn Y(); /* this is the trick; forward-declare Y() */
/* text of X */
}
static yreturn Y()
{
/* text of Y */
}
sreturn S()
{
/* text of S */
}
You might want to put S() up front and forward-declare X() and Y(). That would
look like:
sreturn S()
{
xreturn X();
yreturn Y();
/* text of S */
}
I use a #define forward /*empty*/ so I can write:
sreturn S()
{
forward xreturn X();
forward yreturn Y();
/* text of S */
}
Be aware that there is some theological variation among C compilers on whether
forwards in functions remain in effect for only function scope until the end of
the module file. ANSI C, I believe, assumes the former, and writing as if the
former were true does no harm on compilers that assume the latter.
I gather you're a novice. Congratulations on having learned concern for scope
and visibility issues early. Too many people never break the bad habit C
encourages of leaving their functions and data promiscuously exposed.
--
Eric S. Raymond (the mad mastermind of TMN-Netnews)
Email: eric at snark.uu.net CompuServe: [72037,2306]
Post: 22 S. Warren Avenue, Malvern, PA 19355 Phone: (215)-296-5718
More information about the Comp.lang.c
mailing list