c++parameter-passingfunction-pointersextern-c

Passing a pointer to a function as an argument to a function


Just wondering if anyone can give me some advice regarding where I'm going wrong here. My program works OK if I run it as is, but as soon as I swap the commented line with the one below it, I get errors. My goal is to be able to use the commented line because I want to create a program which let's me pass a pointer to a function as an argument to another function, but so far I'm having no luck.

#include <iostream>
using namespace std;

double arith_op(double left, double right, double (*f)(double, double));
double addition(double left, double right);
double subtraction(double left, double right);
double multiplication(double left, double right);

int main()
{
  double left, right;
  int choice;
  double (*f[3])(double, double) = { addition, subtraction, multiplication };
  
  cout << "Enter 1 for addition, 2 for subtraction, 3 for multiplication "
       << "(-1 to end): " << endl;
  cin >> choice;

  while (choice != -1) {

    cout << "Enter a floating-point number: " << endl;
    cin >> left;

    cout << "Enter another floating-point number: " << endl;
    cin >> right;

    // double* result = arith_op(left, right, f[choice - 1](left, right));
     double result = f[choice - 1](left, right);

    if (choice == 1) {
      cout << left << " + " << right << " = " << result;
    }
    else if (choice == 2) {
      cout << left << " - " << right << " = " << result;    
    }
    else {
      cout << left << " * " << right << " = " << result;    
    }
    cout << endl;

    cout << "Enter 1 for addition, 2 for subtraction, 3 for multiplication "
     << "(-1 to end): " << endl;
    cin >> choice;
  }
}

double arith_op(double left, double right, double (*f)(double, double))
{
  return (*f)(left, right);
}

double addition(double left, double right)
{
  return left + right;
}
double subtraction(double left, double right)
{
  return left - right;
}

double multiplication(double left, double right)
{
  return left * right;
}

I should add that my end goal is to package the function arith_op and the other functions in a seperate file, then use them by including their prototypes with 'extern'. This may be an odd way to approach the problem - it's for an assignment, and they're always odd.

Thank you :)

Wade


Solution

  • Your problem is in the 3rd argument here

    arith_op(left, right, f[choice - 1](left, right));
    

    f[i](left, right) is calling the function to give a double, rather than passing the function pointer to arith_op. Simply remove the parameter list

    arith_op(left, right, f[choice - 1]);