C语言 为什么我可以通过参数太多的指针调用函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7140045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why can I invoke a function via a pointer with too many arguments?
提问by yotamoo
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 doubleargument and returns an int.
这应该指向一个函数,它接受一个double参数并返回一个int.
func2does NOT have any argument, but still when I write:
func2没有任何论点,但当我写:
fp = func2;
fp(2);
(with 2being just an arbitrary number), func2` is invoked correctly.
(2只是一个任意数字), func2` 被正确调用。
Why is that? Is there no meaning to the number of parameters I declare for a function pointer?
这是为什么?我为函数指针声明的参数数量没有意义吗?
回答by Adam Rosenfield
Yes, there is a meaning. In C (but notin C++), a function declared with an empty set of parentheses means it takes an unspecifiednumber 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.
是的,有一定的意义。在 C 中(但不是在 C++ 中),使用空括号集声明的函数意味着它接受未指定数量的参数。当您这样做时,您将阻止编译器检查参数的数量和类型;这是 C 语言被 ANSI 和 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:
未能使用正确数量和类型的参数调用函数会导致未定义的行为。如果您改为使用 的参数列表显式声明您的函数采用零参数void,那么当您分配错误类型的函数指针时,编译器会向您发出警告:
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;
回答by paulsm4
You need to explicitly declare the parameter, otherwise you'll get undefined behavior :)
你需要显式声明参数,否则你会得到未定义的行为:)
int func2(double x)
{
printf("func2(%lf)\n", x);
return 0;
}

