为什么我可以通过带有太多参数的指针调用函数?

发布于 2024-12-01 04:52:23 字数 370 浏览 6 评论 0原文

假设我有这个函数:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

提赋 2024-12-08 04:52:23

是的,有一个意义。在 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;

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:

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;
音盲 2024-12-08 04:52:23

您需要显式声明参数,否则您将得到未定义的行为:)

int func2(double x)
{
    printf("func2(%lf)\n", x);
    return 0;
}

You need to explicitly declare the parameter, otherwise you'll get undefined behavior :)

int func2(double x)
{
    printf("func2(%lf)\n", x);
    return 0;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文