#include <stdio.h>
typedef int Myfunc(int);
Myfunc
is the name of a type; it is a function taking an int
argument and returning an int
.
typedef int (*point_to_myfunc)(int);
point_to_myfunc
is a pointer to a function taking an int
argument and returning an int
. You could also have: typedef Myfunc *ptr_to_myfunc;
if you wished (another name for the same type).
static Myfunc example;
This says 'there exists a function called example
of type Myfunc
'.
static int example(int a)
{
printf("example a=%d\n", a);
return 1;
}
This is a possible implementation of example
. You can't use a typedef name to like Myfunc
in the definition of a function of that type.
static void example2(Myfunc *f)
{
printf("example2\n");
f(2);
}
This is a function that takes a pointer to a Myfunc
. The line f(2);
invokes the function pointed at with the argument 2 and ignores the returned value.
static void example3(int (*)(int));
This declares example3
as a function taking a pointer to a function that takes an int
argument and returns an int
result. It could have been written as static void example3(point_to_myfunc);
or static void example3(ptr_to_myfunc);
or static void example3(Myfunc *);
.
static void example3(int (*point_to_Myfunc)(int))
{
printf("example3\n");
point_to_Myfunc(3);
}
This is an implementation of example3
.
int main(void)
{
point_to_myfunc f = &example;
example2(f);
example3(f);
return 0;
}
This program has a variable f
that's a pointer to a function. Interestingly, you could have:
point_to_myfunc f2 = example;
point_to_myfunc f3 = *example;
Etc. And they all mean the same thing.
You could also invoke them using:
(*f2)(101);
(**f3)(103);
The standard notation for the initialization would use neither the &
nor the *
. If you're an old school C programmer, you may well invoke the function pointer using the (*f2)(101)
notation; before the C89 standard, that was the only way to invoke function pointers. Modern style tends to be f2(101);
instead.