关于函数声明中的函数指针

2021-12-13 00:00:00 function pointers c function-pointers c++
#include<stdio.h>
#include<stdlib.h>

int fun1()
{
    printf("I am fun1.");
    return 0;
}

int fun2(int fun())
{
    fun();
    return 0;
}

int main()
{
    fun2(fun1);
    return 0;
}

上面的程序可以运行了.就我而言,我能理解int fun2(int (*fun)()),但我不知道int fun2(int fun())作品.谢谢.

The above program can run. As far as I am concerned, I can understand int fun2(int (*fun)()), but I do not know how int fun2(int fun()) works. Thank you.

推荐答案

当你写int fun2(int fun())时,参数int fun()转换进入int (*fun)(),它变成完全等同于这个:

When you write int fun2(int fun()), the parameter int fun() converts into int (*fun)(), it becomes exactly equivalent to this:

int fun2(int (*fun)());

当您将数组声明为函数参数时,会发生更熟悉的转换.例如,如果你有这个:

A more famiiar conversion happens in case of array when you declare it as function parameter. For example, if you've this:

int f(int a[100]);

即使在这里参数类型也转换成int*,变成这样:

Even here the parameter type converts into int*, and it becomes this:

int f(int *a);

函数类型和数组类型之所以分别转换为函数指针类型和指针类型,是因为标准不允许将函数和数组传递给函数,也不能你从一个函数返回函数和数组.在这两种情况下,它们都会衰减到它们的指针版本.

The reason why function type and array type converts into function pointer type, and pointer type, respectively, is because the Standard doesn't allow function and array to be passed to a function, neither can you return function and array from a function. In both cases, they decay into their pointer version.

C++03 标准在 §13.1/3 中说(在 C++11 中也是如此),

The C++03 Standard says in §13.1/3 (and it is same in C++11 also),

区别仅在于一个是函数类型而另一个是指向同一函数类型的指针的参数声明是等价的.也就是将函数类型调整为指向函数类型的指针(8.3.5).

Parameter declarations that differ only in that one is a function type and the other is a pointer to the same function type are equivalent. That is, the function type is adjusted to become a pointer to function type (8.3.5).

这里还有一个更有趣的讨论:

And a more interesting discussion is here:

  • 引用函数语法 - 有和没有 &

相关文章