为什么我可以通过带有太多参数的指针来调用函数? [英] Why can I invoke a function via a pointer with too many arguments?

查看:113
本文介绍了为什么我可以通过带有太多参数的指针来调用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有这个功能:

int func2() {
    printf("func2\n");
    return 0;
}

现在我声明一个指针:

int (*fp)(double);

这应该指向一个接受double参数并返回int的函数.

This should point to a function that takes a double argument and returns an int.

func2没有任何参数,但是在我写的时候仍然如此:

func2 does NOT have any argument, but still when I write:

fp = func2;
fp(2);

(2只是一个任意数字),func2`被正确调用.

(with 2 being just an arbitrary number), func2` is invoked correctly.

那是为什么?我为函数指针声明的参数数量没有意义吗?

Why is that? Is there no meaning to the number of parameters I declare for a function pointer?

推荐答案

是的,这是有意义的.在C语言中(但在C ++中为 not ),使用空括号声明的函数表示需要使用 undefined> 个参数.执行此操作时,将阻止编译器检查参数的数量和类型.这是ANSI和ISO对C语言进行标准化之前的一个保留.

Yes, there is a meaning. In C (but not in C++), a function declared with an empty set of parentheses means it takes an unspecified number of parameters. When you do this, you're preventing the compiler from checking the number and types of arguments; it's a holdover from before the C language was standardized by ANSI and ISO.

无法使用正确数量和类型的参数调用函数会导致不确定的行为.如果改为通过使用void的参数列表显式声明函数采用零个参数,则当您分配错误类型的函数指针时,编译器将向您发出警告:

Failing to call a function with the proper number and types of arguments results in undefined behavior. If you instead explicitly declare your function to take zero parameters by using a parameter list of void, then the compiler will give you a warning when you assign a function pointer of the wrong type:

int func1();  // declare function taking unspecified parameters
int func2(void);  // declare function taking zero parameters
...
// No warning, since parameters are potentially compatible; calling will lead
// to undefined behavior
int (*fp1)(double) = func1;
...
// warning: assignment from incompatible pointer type
int (*fp2)(double) = func2;

这篇关于为什么我可以通过带有太多参数的指针来调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆