what is the use of a function pointer?

Under any circumstances I can think of, when I feel I need use a function pointer, I can always use some if and switch statement to replace.

Cannot think of any particular use of a function pointer!!!
Last edited on
closed account (N36fSL3A)
You need them to dynamically load libraries at runtime. Your DLL/SO exports function names, and you load them into your program. From there you use them.
There are also times when using function pointers (especially passing them to functions) is easier. For example, you could write a generic sort function, but rather than having it sort '<' all the time, you could make it take a function pointer of a compare. std::sort is like this, you can call it like so:
1
2
3
4
5
6
7
// sort based on the squares of numbers, in descending order
bool comp(int a, int b) {
    return a*a > b*b;
}

std::vector<int> myvec = {-5, 4, -2, 8, 1};
std::sort(myvec.begin(), myvec.end(), comp);


Also, function pointers can be used for lazy evaluation of functions.
Topic archived. No new replies allowed.