为什么我可以通过带有太多参数的指针调用函数?
假设我有这个函数:
int func2() {
printf("func2\n");
return 0;
}
现在我声明一个指针:
int (*fp)(double);
它应该指向一个接受 double 参数并返回 int 的函数。
func2
没有任何参数,但当我写:(
fp = func2;
fp(2);
2
只是一个任意数字)时, func2` 被正确调用。
这是为什么?我为函数指针声明的参数数量没有意义吗?
Say I have this function:
int func2() {
printf("func2\n");
return 0;
}
Now I declare a pointer:
int (*fp)(double);
This should point to a function that takes a double
argument and returns an int
.
func2
does NOT have any argument, but still when I write:
fp = func2;
fp(2);
(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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,有一个意义。在 C 中(但在 C++ 中则不然),使用一组空括号声明的函数意味着它采用未指定数量的参数。当你这样做时,你会阻止编译器检查参数的数量和类型;它是 C 语言被 ANSI 和 ISO 标准化之前的遗留物。
未能使用正确数量和类型的参数调用函数会导致未定义的行为。如果您使用
void
参数列表显式声明函数采用零个参数,那么当您分配错误类型的函数指针时,编译器会向您发出警告: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.
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:您需要显式声明参数,否则您将得到未定义的行为:)
You need to explicitly declare the parameter, otherwise you'll get undefined behavior :)