我试图查明以下前向声明在 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
,但是 gcc
和 clang
都不会给出任何警告。
我对 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/