开发者

Why can I invoke a function via a pointer with too many arguments?

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 f开发者_运维百科unction pointer?


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;


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜