Say I have a function that takes a function pointer:
int funct(double (*f)(double));
And I pass it a function that doesn’t actually do anything:
double g(double a) { return 1.0;}
//...
funct(g);
Will the compiler optimize out the calls to g? Or will this still have overhead? If it does have overhead, how much? Enough that it is worth overloading the function to receive both function pointers and constant values?
Newer versions of GCC (4.4 and later) can inline and optimize a known function pointer using the option
-findirect-inlining. This only works when GCC also knows all of the code that uses the pointer.For example, the C library function
qsortwill not benefit from this optimization. The compiled machine code for qsort is in the library, it expects a function pointer and the compiler cannot change that.However, if you had your own implementation of qsort and you placed it in a header file or you used the very new GCC link-time optimization features, then GCC would be able to take your calling code, the function pointed to, and your qsort source and compile it all together, optimized for your data types and your comparison function.
Now, the only times that this really matters is when the function call overhead is much larger than the function itself. In your example of a function that does nothing much, using a function pointer is serious overhead. In my example of a qsort comparison, the function pointer call is also quite expensive. But in some other application like Windows event dispatch, it hardly matters.
Since you are using C++ you should study templates. A template function can accept a so-called
function objectwhich is just an object that implementsoperator()and it can accept function pointers. Passing a function object will allow the C++ compiler to inline and optimize almost all of the code involved.