Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 555
yotamoo Avatar asked Aug 21 '11 18:08

yotamoo


People also ask

What happens if a caller passes too many parameters to a function?

Passing many arguments will have no effect to the function, as long as the parameters are filled in.

How many is too many arguments for a function?

Functions with three arguments (triadic function) should be avoided if possible. More than three arguments (polyadic function) are only for very specific cases and then shouldn't be used anyway.

What does too many arguments mean in C?

Too many arguments to function call “c” You declare printsp and printhash without a parameter but you call them with a parameter, this is non consistent. You need a parameter and to use it, and you do not use the value return by the functions so better to have them void.

How many arguments does call take?

apply() is one of JavaScript's built-in methods that you can use to reassign a specific method from one object to a different one. apply() does the same thing as call() . The core difference between the two methods is that apply() accepts only two arguments. In contrast, call() takes as many arguments as you need.


1 Answers

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; 
like image 84
Adam Rosenfield Avatar answered Oct 11 '22 07:10

Adam Rosenfield