Syren said:
Hi,
is it possible to write two functions which both require a function as
an argument and both being able to use the other function as an
argument? Afaik the address of a function is not known upon declaration
but only once its defined.
No, functions are not allowed as arguments to C functions. The result
of a function call is a value that can be passed as an argument.
Function pointers can be passed as an argument. But functions
themselves cannot. If it seems otherwise, it's probably because a
function name is automatically converted into a pointer to the named
function in most contexts. If you're talking about function pointers,
then yes, it is possible.
The tricky detail is declaring the types in the function prototypes.
The problem, as you'll find out if you try it, is that fully declaring
the argument types requires infinite recursion. The solution is, at
some point, to take advantage of the fact that C doesn't require you
to declare the argument type - instead of using a function prototype,
use an old-style function declaration that leaves the argument list
unspecified.
It's very easy, when writing code like this, to produce infinitely
recursive function calls. Remember to insert something to prevent
infinite recursion. In the following rather silly code, 'count' serves
that purpose.
#include <stdio.h>
int func1(unsigned count, int(*f)())
{
printf("func1 +%ux\n", count);
if(count && f != NULL)
count = f(count-1, f);
printf("func1 -%ux\n", count);
return count;
}
int func2(unsigned count, int(*f)())
{
printf("func2 +%ux\n", count);
if(count>0 && f!=NULL)
count = f(count-1,func1);
printf("func2 -%ux\n", count);
return count;
}
int main(int argc, char *argv[])
{
func2(argc, func2);
return 0;
}
Note: if you want func1() to be able to refer to func2 by name the
same way that func2 refers to func1, you'll have to forward declare
func2 before defining func1.