函数作为函数的参数

Function as parameter to function

我刚刚注意到使用 -pedantic -Wallgccclang.

编译时没有任何错误或警告
#include <stdio.h>

int x = 0;

void func(int f(const char *)) {
    f("func()!");
}

int main(void) {
    func(puts);
}

在这种情况下,参数 f 似乎被视为指向函数 int (*)(const char *) 的指针。

但这是我从未见过或听说过的行为。这是合法的 C 代码吗?如果是这样,那么当您将函数作为函数的参数时会发生什么?

这是标准允许的。来自 C99 标准第 6.9.1 章(取自 http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf):

EXAMPLE 2 To pass one function to another, one might say

int f(void);
/*...*/
g(f);

Then the definition of g might read

void g(int (*funcp)(void))
{
    /*...*/
    (*funcp)(); /* or funcp(); ... */
}

or, equivalently,

void g(int func(void))
{
     /*...*/
     func(); /* or (*func)(); ... */
}