我们能否将特定签名的函数地址放入定义为具有其他签名的函数指针中并无缝使用它?
例如下面的代码
#include <stdio.h>
void print_n(int *pn) {
printf("%d\n", *pn);
}
void print_n_wrapper(void *p) {
print_n(p);
}
int main(void) {
int n = 123;
void (*f)(void *) = print_n_wrapper;
f(&n);
f = print_n;
f(&n);
return 0;
}
在我的机器上编译并运行良好。我是否以某种方式调用了未定义的行为?
最佳答案
是的,是undefined behaviour .
引用 C11
,章节 §6.3.2.3,指针,(强调我的)
A pointer to a function of one type may be converted to a pointer to a function of another type and back again; the result shall compare equal to the original pointer. If a converted pointer is used to call a function whose type is not compatible with the referenced type, the behavior is undefined.
关于“类型不兼容的函数”部分,兼容性的定义如下
For two function types to be compatible, both shall specify compatible return types.(146) Moreover, the parameter type lists, if both are present, shall agree in the number of parameters and in use of the ellipsis terminator; corresponding parameters shall have compatible types.
这意味着,void *
和 int *
应该是相同的类型,但它们不是 .因此,这些函数也不是兼容类型。
关于一对指向采用不同类型参数的不同函数的指针可以兼容吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31609662/