Any modern compiler can (and will) easily optimize out (i.e. inline) calls made through function pointers is situations when the compiler knows where the pointer is pointing to at compile time.
In your specific example in general case the value of the pointer cannot be predicted at compile time at the point of the call, since it is passed from outside as a parameter of function funct
. In situations when the function funct
itself is small enough to get inlined, the run-time parameter gets eliminated and the whole code of funct
gets "dissolved" in the funct
s caller context. In the value of the pointer is known in that caller context, then, again, the compiler can easily eliminate the call through the pointer.
Finally, if the function funct
is relatively heavy (meaning it does not get inlined), the you should probably expect the compiler to generate an ordinary run-time call through the pointer from inside of funct
. The potential for call elimination exists in this case as well, since the compiler can theoretically generate a separate version of funct
for each compile-time value of g
. For example, if you have
int funct(int x1, int x2, int x3, double (*f)(double));
which is called with only two possible arguments for parameter f
funct(rand(), rand(), rand(), g1);
...
funct(rand(), rand(), rand(), g2);
then the compiler can "reduce" it into two functions
int funct_g1(int x1, int x2, int x3);
int funct_g2(int x1, int x2, int x3);
without a function pointer parameters and with direct calls to either g1
and g2
inside. (Of course, this optimization is not in any way tied to function pointers and can be applied to any function parameter that is used with only a small fixed set of arguments. In fact, this is similar to C++ templates.) But I'm not aware of any compilers that would do anything like that.