C 中函数类型的前向声明

Jor*_*ter 5 c recursion types function go

我想在 C 中声明一个递归函数类型(声明自身的函数)。

\n

在像 Go 这样的语言中我可以这样做:

\n
type F func() F\n\nfunc foo() F {\n  return foo\n}\n
Run Code Online (Sandbox Code Playgroud)\n

如果我尝试在 C 中做同样的事情:

\n
typedef (*F)(F());\n
Run Code Online (Sandbox Code Playgroud)\n

我从 GCC 收到以下错误:

\n
main.c:1:14: error: unknown type name \xe2\x80\x98F\xe2\x80\x99\n    1 | typedef (*F)(F());\n
Run Code Online (Sandbox Code Playgroud)\n

这是有道理的,因为 F 在使用时并不存在。前向声明可以解决这个问题,如何在 C 中前向声明函数类型?

\n

ike*_*ami 6

C 不支持递归类型定义。

例外:您可以使用指向尚未声明的结构类型的指针,因此结构类型可以包含指向正在声明的结构类型的结构的指针。

此外,您显然可以使用尚未声明为函数的返回值的结构类型。所以这很接近你想要的:

// This effectively gives us
// typedef struct { F *f } F( void );

typedef struct S S;

typedef S F( void );

struct S {
   F *f;
};

S foo() {
   return (S){ foo };
}

int main( void ) {
   F *f = foo;
   printf( "%p\n", (void*)f );

   f = f().f;
   printf( "%p\n", (void*)f );
}
Run Code Online (Sandbox Code Playgroud)