I am trying to implement a function that takes in 2 function pointers as parameters and the function pointers will then call the correct/appropriate functions and execute accordingly. I am having trouble thinking of how to correctly create the prototypes for the function which takes in function pointers.
Note the function call in main is given to be exactly func(clear_prod, prod).
These are given as well:
void sum(double x) { _result = x; }
void prod(double x) { _result *= x; }
and
void clear_sum() { _result = 0; }
void clear_prod() { _result = 1.0; }
My task was to implement double func(a, b) but I do not know how to declare the function prototype and keep getting an implicit declaration error.
What func does is it takes 2 constant global variables (example int 5 and 10) and based on the parameters given to func, will return its sum or product.
Example:
Global variables are int _result, int x = 5 and int y = 2.
func(clear_sum, sum) will return 7.
func(clear_prod, prod) will return 10.
The given incomplete func declaration is given to be:
double func(clear, op) {
// enter body;
return _result;
}
CodePudding user response:
It is very unclear what you want.
I am trying to implement a function that takes in 2 functionPointers as parameters
Here you have an example how function pointers work.
typedef int func(int, int);
int add(int a, int b)
{
return a b;
}
int mul(int a, int b)
{
return a * b;
}
int bar(func *f1, func *f2, int a, int b, int c)
{
if(a) return f1(b,c);
else return f2(b,c);
}
int main(void)
{
printf("%d\n", bar(add, mul, 0, 5, 7);
printf("%d\n", bar(add, mul, 1, 5, 7);
}
CodePudding user response:
Instead of having a global result variable, it's better to let the sum and product functions return the result of an accumulator plus or times the next element in the array. Here is one way to do it:
#include <stdio.h>
#define LEN(array) (sizeof (array) / sizeof (array)[0])
typedef double (*Reducer)(double acc, double x);
double Reduction(Reducer f, double x0, const double a[], int aLen)
{
double result;
int i;
result = x0;
for (i = 0; i < aLen; i ) {
result = f(result, a[i]);
}
return result;
}
double Sum(double acc, double x)
{
return acc x;
}
double Product(double acc, double x)
{
return acc * x;
}
int main(void)
{
double sum, product;
const double a[] = {1.0, 2.0, 3.0, 4.0};
sum = Reduction(Sum, 0.0, a, LEN(a));
product = Reduction(Product, 1.0, a, LEN(a));
printf("sum = %f\n", sum);
printf("product = %f\n", product);
return 0;
}
