Home > Enterprise >  How do you pass a function pointer to a function in c?
How do you pass a function pointer to a function in c?

Time:04-26

#include "stdio.h"
int add(int x, int y)
{
    return x   y;
}
int withFive(int x, int (*func))
{
    return (*func)(x,5);
}
int main()
{
    void (*funcptr)(int) = &add;
    printf("%d", withFive(10,funcptr));
    return 0;
}

This code seems like it would compile based on my understanding of function pointers but there is an error that a function or function pointer isn't being passed to withFive. How should I write withFive so that the compiler will accept the argument as a function ptr?

CodePudding user response:

The definition should be

int withFive(int x, int (*func)(int, int ) )

or

int withFive(int x, int (*func)(int x, int y) )

like in a variable definition.

Btw: void (*funcptr)(int) = &add; should be int (*funcptr)(int,int) = &add; as well or just int (*funcptr)(int,int) = add;

CodePudding user response:

int withFive(int x, int (*func))

You want, as an argument, a function func that returns int and takes two int as parameter.

So you need:

int withFive(int x, int (*func)(int, int))

Then:

{
    return (*func)(x,5);
}

You don't need to dereference func. Just write

return func(x, 5);

Then:

void (*funcptr)(int) = &add;

That's the wrong type again. And you don't need to take the address of add. Just write:

int (*funcptr)(int, int) = add;

Or you could just write:

printf("%d", withFive(10,add));

CodePudding user response:

In your case it would have to be int withFive(int x, int (*func)(int,int)). However, using the raw function pointer syntax of C is quite unreadable. The recommended practice is to always use typedefs, like this:

typedef int operation_t (int x, int y); // function type acting as "template"

int add (int x, int y);
int withFive(int x, operation_t* op); // op is a pointer to function
...

withFive(10, add);
  • Related