c - 当您在 C 语言中声明参数数量错误的回调时会发生什么?

标签 c pointers callback

因此,我正在我工作的公司中实现一项功能,我对回调和函数指针有一些疑问。这是一个示例代码:

struct callback {
    int (*func) (int *, int);
};

static struct callback cbstruct;

void install_func(struct callback *cbstruct, int (*func) (int *, int))
{
    cbstruct->func = func;
}

int write(int *integ)
{
    return *integ;
}

int main() {
    int * a = malloc(sizeof(a));
    *a = 5;

    install_func(&cbstruct, write);

    printf("%d\n", (cbstruct.func)(a,3));
    return 0;
}

如您所见,此程序使用函数指针为结构注册回调。预计该函数接收两个参数(int* 和 int),但在示例代码中,“write”函数只接收一个 int *。

我希望它会给我一个编译错误,但只有一个警告:

funcpointer.c:24:26: warning: passing argument 2 of ‘install_func’ from incompatible pointer type
install_func(&cbstruct, write);
                          ^
funcpointer.c:10:6: note: expected ‘int (*)(int *, int)’ but argument is of type ‘int (*)(int *)’
void install_func(struct callback *cbstruct, int (*func) (int *, int))
     ^

这个程序显然运行正确,在屏幕上打印了 5,但考虑到定义和声明中参数数量的差异,我不确定它是否正确编写。

为什么它可以编译并工作(显然)?这样做有没有迫在眉睫的问题?我不确定从 main 调用的第二个参数 (3) 会发生什么。

我问这个问题是因为我最近更改了回调的签名(添加参数),并且我期望从调用此回调的地方看到很多错误,但我只是收到一些警告并且程序继续(显然)正确运行。

谢谢!

最佳答案

§6.3.2.3 中的标准 C11 指定:

  1. 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.

因此您可以在不同类型的函数指针之间进行转换,但明确指出,如果调用与引用的指针不兼容,这会带来未定义的行为。

关于c - 当您在 C 语言中声明参数数量错误的回调时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34774530/

相关文章:

c++ - 自动化 "yes"以打开 SSH 命令

c - 将第i个数组指针设置为c中的变量

c - 计算 C 代码的圈复杂度的工具

c - 为什么 Clang 支持取消引用未初始化的指针

c - 指向作为操作链表的函数参数的指针

javascript - Eloquent JavaScript 中的removeEventListener 示例

c - 在C中获取附近的Wifi

c - 限制结构体中的指针

javascript - 如何从字符串调用函数?

javascript - 如果我们可以在高阶函数体内调用回调函数,为什么还要将它们作为参数传递呢?