gpt4 book ai didi

c - 为什么函数参数列表中的函数指针可以省略 `(*)`?

转载 作者:太空狗 更新时间:2023-10-29 16:33:50 24 4
gpt4 key购买 nike

用 gcc8 编译:

#include <stdio.h>
void some_func(void f1(void), void (*f2)(void))
{
printf("%d\n", f1);
printf("%d\n", f2);
}

(仅)给出以下警告:

<source>:11:14: warning: format '%d' expects argument of type 'int', but argument 2 has type 'void (*)(void)' [-Wformat=]
printf("%d\n", f1);
<source>:12:14: warning: format '%d' expects argument of type 'int', but argument 2 has type 'void (*)(void)' [-Wformat=]
printf("%d\n", f2);

为什么f1的类型和f2的类型一样?只有 f2 被声明为函数指针。我希望 f1 根本不会编译,因为它命名的是函数类型,而不是函数指针。函数参数列表中的函数类型更改为指向该函数类型的指针的规则是什么?

最佳答案

因为标准 ( 6.7.6.3p8 ) 是这样说的

A declaration of a parameter as ''function returning type'' shall be adjusted to ''pointer to function returning type'', as in 6.3.2.1.

这类似于arrays parameters are adjusted to pointers (6.7.63.p7) ,如果你考虑一下。

void some_func(void (void));
void some_func(void (*)(void));

是兼容的声明,就像:

void other_func(char string[]);
void other_func(char *string);

是。


请注意,调整不会使 void some_func(void (*)(void)void some_other_func(void (**)(void)void yet_another_func(void (*****)(void) 并且就函数而言,声明不再真正反射(reflect)使用,(尽管这是语言原作者的意图) . 在标准 C 中,由于函数标识符如何退化为指针,以及使用函数类型还是函数指针类型进行调用无关紧要,您可以使用任意多个 * 调用任何函数:

#include <stdio.h>
int main()
{
(*puts)("hello world");
(******puts)("hello world");
(***&*&*puts)("hello world"); //& cancels a * as per 6.5.3.2p3

int (*p)(char const*) = puts;
int (**pp)(char const*) = &p;
int (***ppp)(char const*) = &pp;

(**ppp)("hello world"); //at least two asterisks required here
}

关于c - 为什么函数参数列表中的函数指针可以省略 `(*)`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52996650/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com