a question on function returning a pointer to a function 
Author Message
 a question on function returning a pointer to a function

     What is wrong with the following piece of code (at compile-time)?

int a(int p);
int b(float p);

int (*which_funct(s))()
char *s;
{
  if (!stricmp(s,"A"))
    return(a);
  if (!stricmp(s,"B"))
    return(b);

Quote:
}

cc (on a Sun) doesn't complain at all. Neither does VAX-11 C. gcc
however gives an error about the last line (line 10) - incompatible
types. I've been told that it is because I didn't specify (in the
definition of which_funct()) what type of argument the function to
which I'm trying to return a pointer takes. But, what if I want to
return functions which take different arguments, like in the above
example? I want which_funct() to return a pointer to either function
A, which takes an int, or function B, which takes a float. What should

Mike Levin



Sat, 29 Apr 1995 20:29:52 GMT  
 a question on function returning a pointer to a function

Quote:
> int a(int p);  int b(float p);
> int (*which_funct(s))() char *s;
> { [conditionally return(a) or return(b)] }
> cc (on a Sun) doesn't complain at all.  Neither does VAX-11 C.  gcc
> however gives an error about the last line (line 10) - incompatible
> types.

Because int (*)() (the return type) matches neither int (*)(int) (the
type of a) or int (*)(float) (the type of b).

It may be that gcc complains about b and not a because the argument
type doesn't match what would occur in the presence of default
promotions for an old-style argument list for b, but this isn't the
case for a.

Quote:
> [W]hat if I want to return functions which take different arguments,
> like in the above example?

Cast them.  return((int (*)())a) and return((int (*)())b) should work
just fine.

Of course, you must cast the returned pointer back to the correct type
before actually calling through it.

                                        der Mouse




Tue, 02 May 1995 05:07:24 GMT  
 
 [ 2 post ] 

 Relevant Pages 

1. Question about signal()/pointers to functions that return pointers to functions

2. Pointer to function returning pointer to function returning...

3. QUESTION: functions returning pointers to functions

4. How to use (pointer to function), and function and pointer to (pointer to function)

5. Function returning a function-pointer - how to prototype ?

6. Declaring static function returning pointer to extern function

7. About function that returns function pointer

8. Function returning pointers to functions (repost)

9. Function returning pointers to functions

10. (member) function returning pointer to functions like itself?

11. functions returning pointers to functions

12. Function returning a function pointer.

 

 
Powered by phpBB® Forum Software