CKTIS / C
Pointer to a function that takes no parameters and returns `int`
`int (*fn)(void)` declares a pointer to a function that takes no parameters and returns `int`. Use it to pass a test callback to `run_test`.
Version: ISO C23; implementation support may vary
Syntax
int (*fn)(void);
int run_test(int (*fn)(void));int (*fn)(void) declares fn as a pointer to a function that takes no parameters and returns int. The parentheses around *fn matter: int *fn(void) instead declares a function that returns a pointer to int. A lone void in the parameter list means no parameters, not no return value.
In run_test(check), the function name check is implicitly converted to a pointer to that function; run_test(&check) also works. Inside run_test, both fn() and (*fn)() call the same function indirectly, with no arguments. run_test returns the call's int result.
A call such as fn(1) violates a language constraint and requires a diagnostic. Before the call, fn must point to a function of compatible type. Calling through a null pointer or through a pointer cast to hide an incompatible function type has undefined behavior.
In C23, int (*fn)() also specifies no parameters. Before C23, this pointer declaration did not specify the number or types of parameters. Use (void) to make the zero-parameter contract explicit in either case. C23 support varies by implementation.
Examples
#include <stdio.h>
static int check(void)
{
return 42;
}
static int run_test(int (*fn)(void))
{
return fn();
}
int main(void)
{
printf("%d\n", run_test(check));
return 0;
}
Result
42
`run_test` calls `check` through `fn` without arguments, and `main` prints `42` on its own line.
Related lessons
- C · Lesson 60 · Intermediate · Version: 3