Reputation: 1835
What's the real benefit of using pointers to functions instead of those functions itself? Does it make execution faster ? Or does it provide convenience when it's passed to another function?
Upvotes: 3
Views: 5250
Reputation: 121
function pointers are used in many situations where you are not sure which function to call exactly. Lets take an example. you want to sort an array. For that you want to write a generic sort function . Now this sorting function needs to compare the array elements. But since array can have any elements (int, floats, strings, user defined types etc), how this sort function can compare the elements. So, in this case, you can pass the ordering-determining function as an argument to this sort function and based on that it can sort the array. Also, it is usefull in another way as well. Lets say you want to sort an array of string (a string of numbers). you may want to sort it numerrically or in alphabatically.
In this case, when you want to sort nnumerically, you can pass compare function which compares based on the value of string converted to int. and so on...
Upvotes: 0
Reputation: 239382
Function pointers are how you store functions in variables and pass them into other functions. There are no "advantages" over "regular functions", they are completely different things and trying to compare them doesn't make sense. It's like asking "which is better, variables or if statements?"
Function pointers provide a functionality that would otherwise be unavailable.
Upvotes: 2
Reputation: 46037
There are situations where you must use a pointer to function, there is no other way. For example, to implement a callback function, specifying comparator function(the last parameter in sorting routines).
EDIT: As specified in the comment, this is about C. Function pointer came from C.
Upvotes: 3
Reputation: 8695
In fact passing a pointer of a function is a little bit slower than calling the function itself. But the difference is so little that it can hardly ever have any effect.
As Jon said, it brings more flexibility in some cases, when you can pass the function from one part of your programm to another.
Upvotes: 0
Reputation: 437534
It enables you to "select" a component of your business logic around at run time -- contrast this with hardcoding the function names, which limits you to choosing which function to use at compile time.
Upvotes: 6