如何声明一个函数指针,returns一个函数指针

How to declare a function pointer that returns a function pointer

如何声明指向具有相同参数的函数的函数指针以及returns指向具有相同参数的函数的指针。

funcPtr 指向 func1(int a, int b)func1 returns 指向另一个函数 func2(int a, int b)func2 也是 returns 具有与 func1 相同签名的函数指针。

TYPE funcPtr = func1;
funcPtr = funcPtr(0, 1);

如何申报funcPtrTYPE 应该是什么?

无法解析的自引用

这是不可能直接做到的。如果你试图定义一个函数指针类型,其中函数的 return 类型是它自己的类型,你将 运行 变成一个未解析的自引用,这将需要无限递归来解析。

typedef funcType (*funcType)(void);

Return一个struct

您可以改为将函数 return 声明为一个结构,并且该结构可以包含指向此类函数的指针。

struct func {
    struct func (*func) (void);
};

struct func foo (void);
struct func bar (void);

struct func foo (void) { return (struct func){ bar }; }
struct func bar (void) { return (struct func){ foo }; }

...
    struct func funcPtr = { foo };
    funcPtr = funcPtr.func();

Return 不同的函数指针类型

如果您更喜欢严格使用指针,则需要求助于定义 return 不同函数指针类型的函数。因此,调用的结果必须在调用之前转换回正确的指针类型。

typedef void (*funcPtrType)(void);
typedef funcPtrType funcType(void);

funcType foo;
funcType bar;

funcPtrType foo (void) { return (funcPtrType)bar; }
funcPtrType bar (void) { return (funcPtrType)foo; }

...
    funcType *p = foo;
    p = (funcType *)p();

Return一个指数

您可以将函数定义为 return table 的索引,代表应调用的函数。

enum funcEnum { fooEnum, barEnum };
typedef enum funcEnum (*funcType)(void);

enum funcEnum foo (void) { return barEnum; }
enum funcEnum bar (void) { return fooEnum; }

funcType funcTable[] = { [fooEnum] = foo, [barEnum] = bar };

...
    funcType p = funcTable[fooEnum];
    p = funcTable[p()];

这是在评论和 中提出的,但为了完整起见在此呈现。

这只是一个没有 typedef 的例子。您可以尝试更改函数的参数,但语法很糟糕且通常无用。

char (*(*((*foo)()))())()

foo 是指向函数的指针,返回指向函数的指针,返回指向返回 char 的函数的指针

或者你可以使用 typedefs

例如

typedef int (*foo2)(int, int);

typedef foo2 (*foo1)(int, int);
typedef foo1 (*foo)(int, int);

或更一般

typedef int (*foo`n`)(int, int);
typedef foo`n' (*foo'n-1`)(int, int);

...

typedef foo2 (*foo1)(int, int);
typedef foo1 (*foo)(int, int);

我认为 C 中的真正问题是你得到一个 无限声明 因为函数 return 是一个函数指针并且该函数指针需要输入到 return 需要键入的函数指针....

下面是这样一个无限声明的几个步骤,只是为了展示声明如何扩展和扩展:

int f0(int a) {
    return 1;
}
int (*f1(int a))(int) {
    return f0;
}
int (*(*f2(int a))(int))(int) {
    return f1;
}


作为遗留代码的解决方案,它可以return一个状态编号和一个table带有函数的函数可以用来调用为状态定义的函数,例如:

#define STATE0 0
#define STATE1 1

int fx1(int a);
int fx2(int a);

int (*ftab[])(int) = {
    fx1,
    fx2
};

void examplefunc(void)
{
    int x = ftab[STATE1](3);  // example of calling function from table
}