Path: utzoo!attcan!uunet!mcsun!ukc!edcastle!aiai!richard From: richard@aiai.ed.ac.uk (Richard Tobin) Newsgroups: comp.lang.c Subject: Re: "dummy" functions. Message-ID: <3743@skye.ed.ac.uk> Date: 12 Nov 90 20:16:03 GMT References: <7126@castle.ed.ac.uk> Reply-To: richard@aiai.UUCP (Richard Tobin) Organization: AIAI, University of Edinburgh, Scotland Lines: 82 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 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