John Thompson
John Thompson

Reputation: 1684

Passing a function to a function in C++

I have a root finding function with the signature:

double root_find(double f(double), ...) (the ellipsis just meaning that there are some other arguments that aren't relevant to this question.)

I can also declare the function with the signature:

double root_find(double(& f)(double), ...)

Either way, it works. With the second signature it's pretty clear that I'm passing the function f by reference. With the first signature, I have no idea what's going on. Can someone explain?

Upvotes: 1

Views: 58

Answers (3)

David G
David G

Reputation: 96790

Just like arrays, function types are adjusted to pointer-to-function type in a parameter declaration. Thus, double root_find(double f(double)) means double root_find(double (*f)(double)) - a function taking a pointer-to-function.

A reference-to-function and pointer-to-function are essentially the same, but the semantics for references and pointers still apply (references cannot be reassigned while pointers can, etc.). Also, they can both be called as a normal function as the syntax is unambiguously a function call in that case.

Upvotes: 3

Andrey Derevyanko
Andrey Derevyanko

Reputation: 560

I believe in first case it'll be double (*)(double), in second - double (&)(double)

Upvotes: 0

Telokis
Telokis

Reputation: 3389

In both cases, your compiler will decay it to be double (*f)(double).

Upvotes: 0

Related Questions