我们可以使用C中的函数指针调用函数吗?

2 c pointers function-pointers

我们可以使用函数指针调用函数吗?如果有,怎么样?

Ada*_*iss 13

是.琐碎的例子:


// Functions that will be executed via pointer.
int add(int i, int j) { return i+j; }
int subtract(int i, int j) {return i-j; }

// Enum selects one of the functions
typedef enum {
  ADD,
  SUBTRACT
} OP;

// Calculate the sum or difference of two ints.
int math(int i, int j, OP op)
{
   int (*func)(int i, int j);    // Function pointer.

   // Set the function pointer based on the specified operation.
   switch (op)
   {
   case ADD:       func = add;       break;
   case SUBTRACT:  func = subtract;  break;
   default:
        // Handle error
   }

   return (*func)(i, j);  // Call the selected function.
}

Run Code Online (Sandbox Code Playgroud)