functions returning pionters to functions
djh at ccivax.UUCP
djh at ccivax.UUCP
Fri Dec 16 02:39:35 AEST 1983
The declaration 'int (*ptr)()' defines 'ptr' as a pointer to
an integer function. What you want to do is replace 'ptr' with
your function definition of 'getroutine(name, table)', thus
giving 'int (*(getroutine(name, table)))()' which defines
getroutine as a function with two arguements which returns a
pointer to an integer function (or function that returns an
integer).
Note that 'ptr' was replaced by '(getroutine(name, table))'.
The enclosing parenthesis are necessary to bind the arguements
to getroutine before the * (pointer binding) is applied.
Following is a sample program and execution printout.
/*
* functest.c program to test functions that return pointers
* to other functions.
*/
int a() /* define integer function a */
{
printf("In function 'a'\n");
return(1);
}
int b() /* define integer function b */
{
printf("In function 'b'\n");
return(2);
}
int c() /* define integer function c */
{
printf("In function 'c'\n");
return(3);
}
int (*(func(arg)))() /* define function func which returns */
int arg; /* an integer function pointer */
{
switch(arg) {
case 1:
return(a);
case 2:
return(b);
case 3:
return(c);
}
}
main()
{
int (*ptr)(); /* ptr is pointer to integer function */
ptr = func(3);
printf("Returned %d\n",(*ptr)());
ptr = func(1);
printf("Returned %d\n",(*ptr)());
/* ptr = func(2); test without intermediate step */
printf("Returned %d\n",(*(func(2)))());
}
Sample Execution:
In function 'c'
Returned 3
In function 'a'
Returned 1
In function 'b'
Returned 2
Dan Hazekamp
Computer Consoles Inc.
Rochester N.Y.
{siesmo,allegra}!rochester!ccivax!djh
More information about the Comp.unix
mailing list