0

I'm trying to write something simple to understand function pointers and arrays of function pointers. In main, I defined array of function pointers and successfully used it in a range-based for loop. Then I tried to use the same loop in calculate function and I'm getting compilation error. What can be the problem?

#include <iostream>
using namespace std;

double add(double, double);
double minu(double, double);
double multi(double, double);
double div(double, double);
void calculate(double, double, double (*[4])(double, double));

int main(){
    double (*tab[4])(double, double) = {add, minu, multi, div};
    double a, b;
    while(true){
        while(!(cin >> a >> b)){
            cin.clear();
            while(cin.get() != '\n') continue;
        }
        for (double (*f)(double, double) : tab){
            cout << (*f)(a, b) << " ";
        }
        cout << endl;
    }
    return 0;
}

double add(double a, double b){return a + b;}
double minu(double a, double b){return a - b;}
double multi(double a, double b){return a * b;}
double div(double a, double b){return b!=0 ? a/b : 0;}

void calculate(double a, double b, double (*tab[4])(double, double)){
    for (double (*f)(double, double) : tab){
            cout << (*f)(a, b) << " ";
    }
    cout << endl;
}
pykaczka
  • 31
  • 5
  • That's because your function parameter is not really an array. It's an impostor. There's no such thing as function parameters that are arrays, in C++. See the linked question for more information. – Sam Varshavchik Feb 15 '20 at 14:59
  • Oh dear... That's the basic knowledge and I forgot about it. Thank you for pointing this out. – pykaczka Feb 15 '20 at 15:03

0 Answers0