yot*_*moo 23 c function-pointers calling-convention
说我有这个功能:
int func2() {
printf("func2\n");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
现在我声明一个指针:
int (*fp)(double);
Run Code Online (Sandbox Code Playgroud)
这应该指向一个接受double参数并返回一个的函数int.
func2 没有任何争论,但是当我写作时:
fp = func2;
fp(2);
Run Code Online (Sandbox Code Playgroud)
(2只是一个任意数字),func2`被正确调用.
这是为什么?我为函数指针声明的参数数量没有意义吗?
Ada*_*eld 46
是的,有意义.在C(但不是在C++中)中,使用一组空括号声明的函数意味着它需要一个未指定数量的参数.执行此操作时,您将阻止编译器检查参数的数量和类型; 这是C语言由ANSI和ISO标准化之前的延续.
未能使用正确数量和类型的参数调用函数会导致未定义的行为.如果您通过使用参数列表显式声明函数采用零参数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;
Run Code Online (Sandbox Code Playgroud)