Reputation: 136257
Imagine a function myFunctionA with the parameter double and int:
myFunctionA (double, int);
This function should return a function pointer:
char (*myPointer)();
How do I declare this function in C?
Upvotes: 4
Views: 375
Reputation: 91017
void (*fun(double, int))();
According to the right-left-rule, fun
is a function of double, int
returning a pointer to a function with uncertain parameters returning void
.
EDIT: This is another link to that rule.
EDIT 2: This version is only for the sake of compactness and for showing that it really can be done.
It is indeed useful to use a typedef here. But not to the pointer, but to the function type itself.
Why? Because it is possible to use it as a kind of prototype then and so ensure that the functions do really match. And because the identity as a pointer remains visible.
So a good solution would be
typedef char specialfunc();
specialfunc * myFunction( double, int );
specialfunc specfunc1; // this ensures that the next function remains untampered
char specfunc1() {
return 'A';
}
specialfunc specfunc2; // this ensures that the next function remains untampered
// here I obediently changed char to int -> compiler throws error thanks to the line above.
int specfunc2() {
return 'B';
}
specialfunc * myFunction( double value, int threshold)
{
if (value > threshold) {
return specfunc1;
} else {
return specfunc2;
}
}
Upvotes: 4
Reputation: 4347
char * func() { return 's'; }
typedef char(*myPointer)();
myPointer myFunctionA (double, int){ /*Implementation*/ return &func; }
Upvotes: 0
Reputation: 206689
Make a typedef:
typedef int (*intfunc)(void);
int hello(void)
{
return 1;
}
intfunc hello_generator(void)
{
return hello;
}
int main(void)
{
intfunc h = hello_generator();
return h();
}
Upvotes: 3
Reputation: 84159
typedef
is your friend:
typedef char (*func_ptr_type)();
func_ptr_type myFunction( double, int );
Upvotes: 12