mat mat - 2 months ago 7
C Question

Function pointer with some parameters set

How can I create a function pointer to a function where some parameters are set to be fixed upon the definition.

Here is an example what I mean:

Let's say I have the function

int add (int n, int m) {
return n+m;
}


and the function pointer type

typedef int (*increaser)(int);


What I want is a pointer to the function
add
which fixes the first parameter to 1 and leaves the second paramenter open. Something along the lines of

increaser f = &add(1,x);


How can I accomplish this?

Answer

What I want is a pointer to the function add which fixes the first parameter to 1 and leaves the second paramenter open.

There is no such thing in C. The closest you can come is to create a wrapper function and make a pointer to that:

int add1(int x) {
    return add(1, x);
}

increaser f = &add1;

If you don't need a pointer to the function then you can use a macro:

#define increaser(x) add(1, (x))