Function pointer parameter without asterisk

I have seen this definition of a function that receives a function pointer as parameter:

double fin_diff(double f(double), double x, double h = 0.01) { return (f(x+h)-f(x)) / h; } 

I am used to see this definition with an asterisk, i.e.:

double fin_diff(double (*f)(double), double x, double h = 0.01); 

Do you know why the first definition is also valid?

3

3 Answers

Standard says that these two functions are equivalent as function arguments are adjusted to be a pointer to function arguments:

16.1 Overloadable declarations [over.load]
(3.3) Parameter declarations that differ only in that one is a function type and the other is a pointer to the same function type are equivalent. That is, the function type is adjusted to become a pointer to function type (11.3.5).

same in C:

6.7.5.3 Function declarators (including prototypes)
8 A declaration of a parameter as ‘‘function returning type’’ shall be adjusted to ‘‘pointer to function returning type’’, as in 6.3.2.1.

2

Pointers to functions are peculiar. Given a function void f();, you can do

void (*fptr)() = f; void (*fptr)() = &f; void (*fptr)() = &&f; void (*fptr)() = &&&f; 

ad infinitum.

Similarly, when you call a function through a pointer to function you can do

fptr(); (*fptr)(); (**fptr)(); (***fptr)(); 

ad infinitum.

Everything collapses.

4

If a function parameter is specified as a function declaration then the compiler itself implicitly adjusts the parameter as a function pointer.

It is similar to when a function name is passed as an argument of some other function as for example

fin_diff( func_name, 10.0 ); 

the compiler again implicitly converts the function designator to a pointer to the function.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like