[comp.lang.c] Using C with functionals

marks@cbnewsl.att.com (mark.e.smith) (04/22/91)

Maybe the most common high-level program structure problem I've seen over
the years is the problem of handling 'callouts':
for us lowly C programmers, switch statements.

Most C programs use the switch statement for callouts.  A fair amount
of code is 'table driven', (IMHO) wrongfully believing that readability and
extensibility are enhanced by dereferencing function pointers through
arrays indexed by the switch case values.

I've never liked either.  The switch statement is clumsy, and the 
table-driven method usually results in tables where it is difficult to see
what is the relationship between the case and the function.

I was hard pressed to come up with an alternative (besides using 
C++, which I do when I can), until I noticed that in C, you can return
functions from functions.  This means we have a fairly clean way of
defining a table with a function, and we get the same brevity as
with the table driven method.  E.g.:

typedef int ( *PFUN )();	/* the usual function typedef sugar */

int doApple( fruit )
{
	/* ... */
}

int doOrange( fruit )
{
	/* ... */
}

PFUN
table( type )
my_type type;
{
	switch( type ) {
	case APPLE:	return doApple;
	case ORANGE:	return doOrange;
	}
}

main()
{
	/* ... */

	table( fruit_type )( fruit );
}

Anybody use anything like this?  I've never seen code like
this anywhere but in lambda calculus books.  I feel that you are gaining
a little bit over the usual switch statement by exporting the 
switch statement as above; this makes it clear that
the cases must all be 'called out' by functions of the same type, which is
equivalent to what you get in the usual table-driven implementation.

Mark Smith