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?
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;