函数指针没有参数类型?

我试图声明一个指向任何返回相同类型的函数的函数指针。 我省略了指针声明中的参数类型,以查看将生成的错误。 但该程序已成功编译并执行,没有任何问题。

这是正确的声明吗? 我们不应该指定参数类型吗?

#include  #include  void add(int a, int b) { printf("a + b = %d", a + b); } void (*pointer)() = &add; int main() { add(5, 5); return 0; } 

输出:

 a + b = 10 

类型名称中的空括号表示未指定的参数。 请注意,这是一个过时的function。

C11(ISO / IEC 9899:201x)§6.11.6函数声明符

使用带有空括号的函数声明符(不是prototype-format参数类型声明符)是一个过时的function。

void (*pointer)()解释函数指向具有未指定数量的参数。 它与void (*pointer)(void)不相似。 所以后来你根据定义使用了两个成功拟合的参数。

你应该知道几件事……

function声明:

 int myFunction(); 

function原型:

 int myFunction(int a, float b); 
  • prototype是一种特殊的声明,它描述了函数参数的数量和类型。
  • non-prototype函数声明没有说明其参数。

例:

 int myFunction(); 

这个non-prototype函数声明并不意味着myFunction不带参数。 这意味着myFunction采用了不确定数量的参数。 编译器只是关闭参数类型检查,参数检查和myFunction转换。

你可以这样做,

 int myFunction(); // The non-prototype signature will match a definition for // myFunction with any parameter list. // This is the function definition... int myFunction(int x, float b, double d) { ... }