[comp.lang.c] "dummy" functions.

aighb@castle.ed.ac.uk (Geoffrey Ballinger) (11/12/90)

	In a program I am writing I have several versions of a
particular function and I intend to allow the user to select which is
used at run time. To do this I aim to have a "dummy" function which I
will set "equal" to the appropriate function when the user makes his
choice. The rest of my program will then call this "dummy" function -
and hence the correct "real" function - whenever necessary. How do I
declare and assign to this dummy function? I am using the cc compiler
under Sun-OS 4.1. Thanks,

			Geoff.
-- 

 Geoff Ballinger,                           JANET: Geoff@Uk.Ac.Ed
 Department of Artificial Intelligence,      UUCP: ...!mcsun!ukc!Ed.Ac.Uk!Geoff
 Edinburgh University.                 

richard@aiai.ed.ac.uk (Richard Tobin) (11/13/90)

In article <7126@castle.ed.ac.uk> aighb@castle.ed.ac.uk (Geoffrey Ballinger) writes:
>To do this I aim to have a "dummy" function which I
>will set "equal" to the appropriate function when the user makes his
>choice. The rest of my program will then call this "dummy" function -
>and hence the correct "real" function - whenever necessary. How do I
>declare and assign to this dummy function?

The "dummy" function should be declared as "pointer to function 
returning t", where t is the type returned by the various functions.

Suppose that f is the "dummy", and the real functions are f1, f2 ...

The declaration is just like the function declarations, but where you
would have put "f1" put "(*f)".  The parentheses are necessary so that
it is interpreted as "pointer to function returning t" rather than
"function returning pointer to t".

If you assign a function to a function pointer, it is automatically
coerced to a pointer to the function.  You can put an ampersand in to
explicitly make it a pointer, but this will provoke the message
"warning: & before array or function: ignored" from many pre-ansi
compilers (such as Sun's).

To call the function, use (*f)(args).

Below is an example program.  The function (*f) returns its argument
doubled, squared, or unchanged depending on argv[1].  For example,
with arguments 2 and 5 the program will print 25.

-- Richard


#include <stdio.h>

int (*f)();
int f1(), f2(), f3();

int main(argc, argv)
int argc;
char **argv;
{
    switch(atoi(argv[1]))
    {
      case 1:
	f = f1;
	break;
      case 2:
	f = f2;
	break;
      default:
	f = f3;
	break;
    }

    printf("%d\n", (*f)(atoi(argv[2])));

    return 0;
}

int f1(a)
int a;
{
    return a+a;
}

int f2(a)
int a;
{
    return a*a;
}

int f3(a)
int a;
{
    return a;
}


-- 
Richard Tobin,                       JANET: R.Tobin@uk.ac.ed             
AI Applications Institute,           ARPA:  R.Tobin%uk.ac.ed@nsfnet-relay.ac.uk
Edinburgh University.                UUCP:  ...!ukc!ed.ac.uk!R.Tobin