[英]Syntax for a pointer to a function returning a function pointer in C
How to declare a pointer to a function returning another function pointer? 如何声明一个返回另一个函数指针的函数的指针? Please share with me the syntax and an example code snippet.
请与我分享语法和示例代码段。
Also, in which scenario would a function pointer returning a function pointer be used? 另外,在哪种情况下会使用返回函数指针的函数指针?
This is trivial with typedefs: 这对于typedef来说是微不足道的:
typedef int(*FP0)(void);
typedef FP0(*FP1)(void);
FP1
is the type of a pointer to a function that returns a function pointer of type FP0
. FP1
是指向函数的指针类型,该函数返回FP0
类型的函数指针。
As for when this is useful, well, it is useful if you have a function that returns a function pointer and you need to obtain or store a pointer to this function. 至于什么时候这很有用,如果你有一个函数返回一个函数指针,你需要获取或存储一个指向这个函数的指针,这很有用。
If you avoid using typedef
, it is hard. 如果你避免使用
typedef
,那很难。 For example, consider signal()
from the C standard: 例如,考虑来自C标准的
signal()
:
extern void (*signal(int, void (*)(int)))(int);
void handler(int signum)
{
...
}
if (signal(SIGINT, SIG_IGN) != SIG_IGN)
signal(SIGINT, handler);
Using typedefs, it is easier: 使用typedef,它更容易:
typedef void Handler(int);
extern Handler *signal(int, Handler *);
void handler(int signum)
{
...
}
if (signal(SIGINT, SIG_IGN) != SIG_IGN)
signal(SIGINT, handler);
Note that for the signal()
function, you would normally simply use <signal.h>
and let the system worry about declaring it. 请注意,对于
signal()
函数,通常只需使用<signal.h>
并让系统担心声明它。
If you don't want a second typedef, 如果你不想要第二个typedef,
typedef float(*(*fptr_t)(int))(double)
this means " declare fptr_t as pointer to function (int) returning pointer to function (double) returning float " (fptr_t : int → (double → float)) 这意味着“ 声明fptr_t作为指向函数的指针(int)返回指向函数(double)返回float的指针 ”(fptr_t:int→(double→float))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.