0

Given typedef struct covid *covidDB;

I have two functions here:

unsigned long countResult(covidDB cur) {
    unsigned long tmp = 0;
    if (isEmpty(cur)) return 0;
    tmp += countResult(cur->left);
    for (int day = 1; day <= 70; day++) {
        if (cur->patients[day] > 0) {
            tmp += cur->patients[day];
        }
    }
    return tmp + countResult(cur->right);
}

and

void printDB(covidDB cur) {
    if (isEmpty(cur)) return;
    printDB(cur->left);
    for (int day = 1; day <= 70; day++) {
        if (cur->patients[day] > 0)
            show
    }
    printDB(cur->right);
}

Apperently both two functions do inorder traversal through the binary tree. Is it possible to write something like:

void inorder(covidDB cur, /*function*/) {
    //do something
}

and in the main function I call

inorder(root, printList);
inorder(root, countList);
vcth4nh
  • 49
  • 5
  • 2
    You can use function pointers – John Coleman Aug 06 '21 at 07:40
  • 2
    You can define the second argument of your function `inorder` as a function pointer to pass function `printList` or `countList`. Both functions and the function pointer must have the same signature. If e.g. `countList` does some calculation and returns the (preliminary) result, then `printList` must nevertheless accept the same parameters and return something. See https://stackoverflow.com/a/840669/10622916 – Bodo Aug 06 '21 at 07:57

1 Answers1

1

You can do something like that, just you should set the return value types of your passing functions the same as unsigned long:

unsigned long (*func)(covidDB cur);

 void inorder(covidDB cur, unsigned long (*func)(covidD cur)) {
    func(cur);
}
G. Emadi
  • 230
  • 1
  • 8