Martin Thoma
Martin Thoma

Reputation: 136257

How do I declare a function that returns a function pointer?

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

Answers (4)

glglgl
glglgl

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

Fatih Donmez
Fatih Donmez

Reputation: 4347

char * func() { return 's'; }

typedef char(*myPointer)();
myPointer myFunctionA (double, int){ /*Implementation*/ return &func; }

Upvotes: 0

Mat
Mat

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

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84159

typedef is your friend:

typedef char (*func_ptr_type)();
func_ptr_type myFunction( double, int );

Upvotes: 12

Related Questions