c - C 中的未知函数签名

标签 c pointers

如果你能解释一下下面的意思,我将不胜感激:

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/

相关文章:

c - 有没有办法检查 C 字符串中是否存在任何或所有字符?

c - 使用路由套接字需要安装什么包?

c - 为什么数字 51444.325061 不四舍五入到 51444.325 到小数点后 3 位?我想在c编程中四舍五入这个数字

c - 文件 - 我收到错误而不是给出正确的路径

c - 在 C 编程中将枚举指针传递给参数

ios - 将 Canvas 原型(prototype)转换为 iOS 原生

c - C99 中的可变语义

c - fgets() 函数不起作用

c++ - 为 __stdcall 函数指针提供比预期更多的参数

c - 在不修改内容的情况下对数组数据进行排序