4

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?

3
  • 3
    Write a wrapper.. Commented Sep 26, 2016 at 14:42
  • 1
    C does not have closures. Commented Sep 26, 2016 at 14:47
  • I wouldn't call the function type increaser. To me, it is rather an int_unary_operator, as functions implementing this signature can very well do something completely different. Commented Sep 26, 2016 at 14:48

2 Answers 2

3

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))
Sign up to request clarification or add additional context in comments.

Comments

1

C does not support doing this directly. In C++ there is std::function and bind which can achieve this however.

None the less for a pure C solution the closest you can reasonably get is defining a new function that calls add like:

int increment(int input) {
    return add(1, input);
}

Then you can do:

increaser f = &increment;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.