Marcus Rossel
Marcus Rossel

Reputation: 3258

How to create functions within a function and return them?

I want to create a function that returns a function that checks whether a given int is within certain bounds. Therefore the returned function should only take one parameter, an int, and return a bool. This is necessary as the returned function is passed on as a function pointer to another function. So far I would only be able to do it like this:

bool valueIsInBounds(int value) { return value >= 0 && value <= 100; }

int main() {
    functionThatTakesAFunction(&valueIsInBounds);
}

0 and 100 are obviously fixed values, and I would like to change that.
What I would like to be able to do is something like this:

??? functionGenerator(int min, int max) { ??? }

int main() {
    functionThatTakesAFunction(&(functionGenerator(0, 100)));
}

I know this is doable in other languages, though I don't know how this would be achieved in C.

Upvotes: 3

Views: 230

Answers (2)

Paul Ogilvie
Paul Ogilvie

Reputation: 25286

As dynamically generating a function cannot be done in C, the next best approach will be to parametrize the function.

You can pass (as in your question) the bounds as additional parameters, or you can set global or static variables with these bounds.

bool valueIsInBounds(int value, int min, int max) { return value >= min && value <= max; }

int main() {
    functionThatTakesAFunction(valueIsInBounds);
}

or:

int gMin, gMax;
void setBounds(int min, int max) { gMin= min; gMax= max; }
bool valueIsInBounds(int value)  { return value >= gMin && value <= gMax; }

int main() {
    setBounds(0, 100);
    functionThatTakesAFunction(valueIsInBounds);
}

Upvotes: 4

Sorry. As the comments says, this can not be implemented in portable C.

You must generate some assembly yourself to bind the parameters (max & min) to the function pointer. This is called a «trampoline» function, and there exists multiple libraries for that. Here is one: https://www.gnu.org/software/libffcall/trampoline.html

Take a look at this SO post for an better explanation and an example of using the trampoline library above.

Upvotes: 4

Related Questions