There are two ways to call a function in C++:
By name:
f();
Through a function pointer:
typedef void (*fptr_t)();
fptr_t fptr = &f;
(*fptr)();
Now, using the address-of operator on a function name (&f
) obviously creates a function pointer. But the function name can implicitly convert to a function pointer when certain conditions are met. So the above code could be written as:
typedef void (*fptr_t)();
fptr_t fptr = f; // no address-of operator, implicit conversion
(*fptr)();
Your second example is doing exactly this, but using a temporary variable to hold the function pointer instead of a named local variable.
I prefer to use address-of when creating function pointers, the meaning is much clearer.
A related note: The function call operator will automatically dereference a function pointer if one is provided. So this also is legal:
typedef void (*fptr_t)();
fptr_t fptr = &f;
fptr();
That's pretty useful with templates, because the same syntax works whether you have a function pointer or a functor (object implementing operator()
) passed in.
And neither shortcut works with pointer-to-members, there you NEED explicit address-of and dereference operators.
In C, @Mehrdad explains that all function calls use a function pointer.