关于函数声明函数指针 [英] About Pointers To Functions in function declarations

查看:127
本文介绍了关于函数声明函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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(*有趣)()),但我不知道该怎么 INT FUN2(诠释乐趣())的作品。谢谢你。

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乐趣()),参数 INT乐趣()转换成 INT(*有趣)(),就变成完全等价的:

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)());

一个更famiiar转换发生在阵的情况下,当你将它声明为函数参数。例如,如果你这样的:

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 * ,它变成这样:

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:

  • Reference to Function syntax - with and without &

这篇关于关于函数声明函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆