如何制作指向具有不同参数数量的函数的函数指针?

How can I make a function pointer that points to functions with different number of arguments?

我正在尝试实现一个简单的函数指针程序,但收到此警告:

Warning: assignment from incompatible pointer type while assigning function address to function pointer

我的程序如下:

#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int add(int a, int b);
int sub(int a, int b);
int Add3Num(int a, int b, int c);

int main(int argc, char *argv[]) {
  int (*func)(int , ...);
  int a = 20, b = 10, c = 5, result;

  func = add;
  result = func(a, b);  // Warning over here
  printf("Result of 20 + 10 = %d\n", result);

  func = sub;
  result = func(a, b);  // Warning over here
  printf("Result of 20 - 10 = %d\n", result);

  func = Add3Num;
  result = func(a, b, c);  // Warning over here
  printf("Result of 20 + 10 + 5 = %d\n", result);

  return 0;
}

int add(int a, int b){
  return a+b;
}
int sub(int a, int b){
    return a-b;
}
int Add3Num(int a, int b, int c){
  return a+b+c;
}

将指针声明为指向无原型函数(采用未指定数量参数的函数)的指针:

  int (*func)();

那么你的程序应该可以工作,without any need for casts(只要每次调用继续匹配当前指向的函数)。

#include <stdio.h>
int add(int a, int b);
int sub(int a, int b);
int Add3Num(int a, int b, int c);
int main(){
  int (*func)(); /*unspecified number of arguments*/
  int a = 20, b = 10, c = 5, result;

  /*Casts not needed for these function pointer assignments
    because:  */
  func = add;
  result = func(a, b);
  printf("Result of 20 + 10 = %d\n", result);

  func = sub;
  result = func(a, b);
  printf("Result of 20 - 10 = %d\n", result);

  func = Add3Num;
  result = func(a, b, c);
  printf("Result of 20 + 10 + 5 = %d\n", result);
  return 0;
}
/*...*/

对于原型函数,函数指针类型之间的匹配需要或多或少地精确(有一些警告,例如顶级限定符无关紧要,或者可以用不同的方式拼写),否则标准会留下事情未定义。

或者,考虑到无原型函数和函数指针是过时的功能,您可以使用强类型指针(首先是 int (*)(int,int),然后是 int (*)(int,int,int))并使用强制转换来强制转换,这或许是更好的选择。

#include <stdio.h>
int add(int a, int b);
int sub(int a, int b);
int Add3Num(int a, int b, int c);
int main(){
  int (*func)(int , int);
  int a = 20, b = 10, c = 5, result;

  func = add;
  result = func(a, b);
  printf("Result of 20 + 10 = %d\n", result);

  func = sub;
  result = func(a, b);
  printf("Result of 20 - 10 = %d\n", result);

  /*cast it so it can be stored in func*/
  func = (int (*)(int,int))Add3Num; 
  /*cast func back so the call is defined (and compiles)*/
  result = ((int (*)(int,int,int))func)(a, b, c); 
  printf("Result of 20 + 10 + 5 = %d\n", result);
  return 0;
}
/*...*/