my program in C has some functionality (#obviously). The program gets input from the user, this user can then choose different implementations, e.g. myProgram -V1, or myProgram -V2 …
This specification of -V1, -V2, … decides how the function performs a particular calculation.
E.g..
for (int i = 0; i < len; i++) {
i += myFunctionWhichChangesBehaviorOnUserInput(arr[i]);
}
Now I don’t want to create a separate function for each V and then change the respective myFunctionWhichChangesBehaviorOnUserInput() function there.
I know you can do it this way in java.
interface Compute {
double compute(double n);
}
... some imple of Compute
class Task {
Compute compute;
void setCompute(Compute c) {this.compute = c}
double doMyStuff(double[] arr) {
double n = 0;
for (int i = 0; i < arr.length; i++) {
n += compute.compute(arr[i]);
}
return n;
}
}
How can you implement this in C, must be possible somehow.
>Solution :
It sounds like you want function pointers.
#include <stddef.h>
#include <stdio.h>
typedef void (*compute_t)(double);
void printing_a(double);
void printing_b(double);
double arr[5] = {1.0, 2.0, 3.0, 3.5, 4.0};
size_t len = 5;
int main(int argc, char *argv[]) {
compute_t myfunction;
if (argc > 2) {
myfunction = printing_a;
} else {
myfunction = printing_b;
}
for (size_t i = 0; i < len; i++) {
myfunction(arr[i]);
}
}
void printing_a(double n) {
printf("printing_a(%f)", n);
}
void printing_b(double n) {
printf("printing_b(%f/2)", n*2.0);
}
You can set the function pointer, and then call the function pointed to by the pointer. This is analogous to your Java code.