如果你能解释一下下面的意思,我将不胜感激:
void bar(char *a, char *b, unsigned short c) // (2)
{
...
}
void (*foo(void))(char *, char *, unsigned short) // (1)
{
return bar;
}
特别是,
- 为什么(1)中没有变量名?
void (*foo(void))
是什么意思?*foo(void)
怎么可以是名字?返回栏
是什么意思?返回bar
源代码的地址,或者bar
的结果,或者其他?- 使这些签名如此复杂有什么特点吗?
- 您能举例说明用法吗?
最佳答案
foo
是一个不接受参数并返回一个指向函数的指针 的函数,该函数接受三个 char *
类型的参数,char *
和 unsigned short
并返回 void
。
这些声明可能会非常困惑,因为它们应该从里到外阅读,并根据需要左右跳动:
foo
是一个东西 ...foo(void)
...显然是一个函数*foo(void)
... 其返回值可以被解引用(*foo(void))(...)
... 然后用这些参数调用void (*foo(void))(...)
... 产生void
类型的值。
您还可以使用 cdecl.org为您解析复杂的声明:
declare foo as function (void) returning pointer to function (pointer to char, pointer to char, unsigned short) returning void
使用示例:
// Immediately call the returned function.
// The similarity to the declaration is no coincidence!
(*foo())("hello", "world", 42);
// Store the returned function pointer for later invocation.
// This time there are no parentheses following the name, because
// this is a variable, not a function.
void (*fnPtr)(char *, char *, unsigned short) = foo();
(*fnPtr)("hello", "world", 42);
如果参数未在函数内部使用,则始终可以省略参数名称。在这种情况下,甚至没有函数主体可以在其中使用它们,因为 foo
的主体不是要传递给参数的对象。
关于c - C 中的未知函数签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72418793/