What's the correct syntax to define a function that returns a pointer to
a function? Specifically, I'd like a function that takes an int, and
returns a pointer to a function that takes an int and returns a string.
I tried this:
gchar *(*f(gint n))(gint)
{
/* logic here */
}
but this doesn't seem to work.
Define "doesn't seem to work." Are you getting a syntax error? A
runtime error? What?
f -- f
f() -- is a function
f(int n) -- that takes an integer
*f(int n) -- and returns a pointer
(*f(int n))() -- to a function
(*f(int n))(int m) -- that takes an integer
char *(*f(int n))(int m) -- and returns a char *
So, apart from the gint/gchar weirdness (I'm guessing this comes from
some API you're using), your definition looks all right to me.
char *foo(int m)
{
/* does something interesting */
}
char *bar(int m)
{
/* does something interesting */
}
char *bletch(int m)
{
/* does something interesting */
}
char *(*f(int n))(int m)
{
char *(*p)(int m);
switch(n)
{
case 0: p = foo; break;
case 1: p = bar; break;
case 2: p = bletch; break;
default: p = NULL; break;
}
return p;
}
int main(void)
{
char *result;
char *(*p)(int m);
int i;
for (i = 0; i < 4; i++)
{
p = f(i);
result = p(123);
if (result)
{
printf("result = %s\n", result);
}
}
return 0;
}