c - 这个函数指针的前向声明在 C 中有效吗?

标签 c function-pointers

我试图查明以下前向声明在 ANSI-C 中是否有效:

第一个文件:

extern void * fptr;   // opaque forward declaration.
int main (void) {
  fptr = NULL;        // set the function pointer to NULL
}

第二个文件:

typedef int (*fptr_t)(int);
fptr_t fptr;         // real declaration of the function pointer

对我来说,这应该是无效的,因为如果用两种不同的类型声明 fptr,但是 gccclang 都不会给出任何警告。

我对 C11 标准的精确点更感兴趣,这些点可以得出它为什么有效(或无效)的结论。


编辑:在 C11 标准中,6.2.7:2 说:

All declarations that refer to the same object or function shall have compatible type; otherwise, the behavior is undefined.

但我找不到如何确定 void* 是否与 fptr_t 兼容。

最佳答案

C99:

6.2.7 Compatible type and composite type

clause 2:

All declarations that refer to the same object or function shall have compatible type; otherwise, the behavior is undefined.

6.7.5.1 Pointer declarators

clause 2:

For two pointer types to be compatible, both shall be identically qualified and both shall be pointers to compatible types.

如果不深入研究标准,很容易看出 void 和函数是不兼容的类型。

我敢打赌这在 C11 中不会改变。长期以来,C 隐含地支持不同的代码和数据空间以及不同大小和表示的代码和数据指针,删除此功能并将语言限制在更小的机器子集上是很奇怪的。因此,请谨慎投票。有证据更好。

关于c - 这个函数指针的前向声明在 C 中有效吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36761879/

相关文章:

java - 正在寻找计算大型矩阵并输出它们的最快方法?

c++ - 如何以编程方式查找为 Linux 中的特定网络设备配置的 IP 地址/网络掩码/网关?

c - 如何从完整字符串中获取子字符串?

c# - C:函数指针与 C# 委托(delegate)相比的不安全示例

c - qsort 函数指针的类型转换

c++ - 指向可变模板静态函数的指针。如何?

c++ - 简单的跨平台剪贴板库?

c - 如何在不引用 c 对象的情况下导入使用 FFI 的 haskell 模块?

c++ - 为什么 C++ 中函数指针返回的数据过期并且无法访问数组的所有元素?

c - 给定3个整数,每个整数执行一个数学运算。输入任何整数并执行其任务,而无需使用比较语句。