in what case should i use function name rather than function pointer

as i know, when assign a function to a variable, it generally decay into a pointer.

1
2
3
4
void fun(){;}

auto pt = fun; // type of pt is void (*)()
auto& reffun = fun; // type of reffun is void() 

But i can not seek out a situation when this minor difference matters.Are there any actually meaning of this difference?
Last edited on
I don't think it matters unless you want to be able to reassign to the variable.
In general, a "direct" function call (by "function name") is more efficient, because the compiler can translate it into a jump instruction with fixed (i.e known at compile-time) destination address. Possibly, the compiler even performs function inlining in this case. Meanwhile, an "indirect" function call, i.e. from a function pointer (variable), requires loading the target address, from the memory address where the pointer (variable) is stored, first. Also, function inlining won't be possible, because the actual function to be called is only known at runtime.

(That is unless, in very simple situations, the compiler is able to eliminate the indirection)
Last edited on
Perhaps it's analogous to why you may want to use references in general over pointers: With a reference, it's hard to make it null, but a pointer can legally be null. But you can use pointers in more places than references.
Topic archived. No new replies allowed.