一对指向采用不同类型参数的不同函数的指针可以兼容吗?

标签 c function-pointers language-lawyer undefined-behavior

我们能否将特定签名的函数地址放入定义为具有其他签名的函数指针中并无缝使用它?

例如下面的代码

#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/

相关文章:

指向未确定类的成员函数的指针的 C++ 模板,具有不同的参数,称为参数

c++ - 如何将函数指针中的函数保存为类的成员函数?

c - 将函数指针从 Fortran 传递到 C,与 c_f_procpointer 相反

javascript - DOM - 同时事件的计时与 setTimeout

c - 这个函数返回什么

c - 使用结构时的 mmap 偏移量

c - 将 PORTD 值存储在 pic18f452 的数组中 (C)

perl - 为什么在没有粗逗号和严格的 `use` 行上允许使用前导连字符选项?

关于 realloc 函数的困惑

c++ - "Clock arithmetic"/congruent math 中的一个加法/减法函数?