I am coding in C. I would like to pass a function that accepts two parameters with one parameter set to a value into a function that accepts a function with one parameter as input.
void fTwoParameters( float a, float b ){
}
void outerFunction( void (*fOneParameter)(float) ){
}
void main( void ){
// How can I do that?
for( int i=1, i<1000, i++ ){
// I would like to pass fTwoParameters into outerFunction with b set to the value of i
outerFunction( /* Problem is Here */ )
}
}
I think that this can be done with global variables. Is there a way to do it without a global variable?
Unfortunately standard C won’t help you much here. You can set a global variable though these tend to make the program harder to understand down the line.
The standard way of solving this issue is to make sure that any function outer
that you define and which accepts a pointer to another function inner
, accepts an argument which is just passed to inner
. (Very often this argument will be void*
, in particular in the case of libraries so that it can pass anything.)
int inner(int x, void* user_data) {
int y = *((int*)user_data);
return x * y;
}
int outer(int (*inner)(int, void*), void* user_data) {
return inner(42, user_data);
}
int main(void) {
int y = 17;
return outer(&inner, &y);
}
If you are using GCC, you can use nested functions, but beware that these are a GNU extension and may not work with other compilers.
float twoParameters(float a, float b) {
return a * b;
}
void main(void) {
const float a = 42.0;
float oneParameter(float b) {
return twoParameters(a, b);
}
outerFunction(&oneParameter);
}