This is my first post on StackOverflow, so I hope the format will be okay.
I want to pass functions as parameter to another function. To that end, I declare a struct to describe functions. But then, I get an invalid analyser error on compilation.
In functions.h, I have this bit:
struct double_fun{
double (*function)(double x);
};
// Test functions.
extern struct double_fun square;
// Other test functions
// Exponential function.
extern double exponential_temp(double x,double temperature);
extern struct double_fun exponential(double temperature);
Then in functions.c:
// Test functions for somme.
double square_fun(double x){
return x*x;
}
struct double_fun square = square_fun();
// Other test functions
// Exponential function.
double exponential_temp(double x, double temperature){
return exp(x/temperature); // From math.h
}
struct double_fun exponential(double temperature){
double aux_fun(double x){return exponential_temp(x, temperature);};
struct double_fun aux = aux_fun;
return aux;
}
double somme(double* liste, int length, struct double_fun fun){
double poids = 0;
for(int i=0;i<length;++i){
poids = poids + (fun.function)(liste[i]);
}
return poids;
}
My ultimate goal is to use somme(list, length, function) to apply a function to a list then return the sum of the elements (in particular with the exponential function). But in another file where I call somme, I call it several times for different values of temperature. This is why I have exponential(temperature) which is supposed to return a function depending on the value of temperature.
This is the error I get:
make learning
gcc -Iinclude/ -o source/functions.o -c source/functions.c -Wall -Werror -lm
source/functions.c:83:28: error: invalid initializer
83 | struct double_fun square = square_fun;
| ^~~~~~~~~~
[[Same error for other test functions]]
source/functions.c: In function ‘exponential’:
source/functions.c:104:29: error: invalid initializer
104 | struct double_fun aux = aux_fun;
| ^~~~~~~
make: *** [Makefile:21 : source/functions.o] Erreur 1
I tried to use no struct and return pointers towards functions instead, and it worked for the test functions, but then there seemed to be no valid syntax for exponential(temperature) that would return a function depending on temperature. On StackOverflow, I found several explanations of how to pass functions as parameters, but no example allows me to have temperature as a parameter without being an argument.
If you could help me either get around this error or find another way to pass a function as parameter to somme, I would be very grateful!