Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C change behavior of function on behalf of input

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..

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading