"dummy" functions.

Richard Tobin richard at aiai.ed.ac.uk
Tue Nov 13 07:16:03 AEST 1990


In article <7126 at castle.ed.ac.uk> aighb at 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 at uk.ac.ed             
AI Applications Institute,           ARPA:  R.Tobin%uk.ac.ed at nsfnet-relay.ac.uk
Edinburgh University.                UUCP:  ...!ukc!ed.ac.uk!R.Tobin



More information about the Comp.lang.c mailing list