gpt4 book ai didi

c - 在 C 中,为什么我可以将函数名(不是指针)作为参数传递给函数?

转载 作者:行者123 更新时间:2023-12-01 19:39:28 25 4
gpt4 key购买 nike

<分区>

我测试了以下代码:

#include <stdio.h>
void f(void g()) {
g();
}

void g(void) {
printf("hello, world\n");
}

int main() {
f(g);
return 0;
}

效果很好。在上面的代码中,为什么在c中我们可以将函数名g作为参数,将函数原型(prototype)作为参数呢?

在 K&R 一书中,它说我们可以使用指向函数的指针:所以我可以这样定义函数 f:

void f(void (*g)()) {
g();
}
void g(void) {
printf("hello, world\n");
}

int main() {
void (*pf)() = g;
f(pf);
f(g); // Here f(g) also works.
return 0;
}

所以在第一种f定义形式中,参数原型(prototype)为void g(),在第二种形式中参数原型(prototype)为void(*g) ()。为什么f的两种定义形式是一样的?

而在第二种形式中,参数是指向函数的指针,为什么 f(g) 也有效?

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