What is the point of function pointers?

2020-01-22 13:09发布

I have trouble seeing the utility of function pointers. I guess it may be useful in some cases (they exist, after all), but I can't think of a case where it's better or unavoidable to use a function pointer.

Could you give some example of good use of function pointers (in C or C++)?

16条回答
Anthone
2楼-- · 2020-01-22 13:31

In C, the classic use is the qsort function, where the fourth parameter is pointer to a function to use to perform the ordering within the sort. In C++, one would tend to use functors (objects that look like functions) for this kind of thing.

查看更多
We Are One
3楼-- · 2020-01-22 13:31

Function pointers can be used in C to create an interface against which to program. Depending on the specific functionality that is needed at runtime, a different implementation can be assigned to the function pointer.

查看更多
\"骚年 ilove
4楼-- · 2020-01-22 13:32

I used function pointers recently to create an abstraction layer.

I have a program written in pure C that runs on embedded systems. It supports multiple hardware variants. Depending on the hardware I am running on, it needs to call different versions of some functions.

At initialization time, the program figures out what hardware it is running on and populates the function pointers. All of the higher-level routines in the program just call the functions referenced by pointers. I can add support for new hardware variants without touching the higher-level routines.

I used to use switch/case statements to select the proper function versions, but this became impractical as the program grew to support more and more hardware variants. I had to add case statements all over the place.

I also tried intermediate function layers to figure out which function to use, but they didn't help much. I still had to update case statements in multiple places whenever we added a new variant. With the function pointers, I only have to change the initialization function.

查看更多
Animai°情兽
5楼-- · 2020-01-22 13:33

Use of function pointer

To call function dynamically based on user input. By creating a map of string and function pointer in this case.

#include<iostream>
#include<map>
using namespace std;
//typedef  map<string, int (*)(int x, int y) > funMap;
#define funMap map<string, int (*)(int, int)>
funMap objFunMap;

int Add(int x, int y)
{
    return x+y;
}
int Sub(int x, int y)
{
        return x-y;
}
int Multi(int x, int y)
{
        return x*y;
}
void initializeFunc()
{
        objFunMap["Add"]=Add;
        objFunMap["Sub"]=Sub;
        objFunMap["Multi"]=Multi;
}
int main()
{
    initializeFunc();

    while(1)
    {
        string func;
        cout<<"Enter your choice( 1. Add 2. Sub 3. Multi) : ";
        int no, a, b;
        cin>>no;

        if(no==1)
            func = "Add";
        else if(no==2)
            func = "Sub";
        else if(no==3)
            func = "Multi";
        else 
            break;

        cout<<"\nEnter 2 no :";
                cin>>a>>b;

        //function is called using function pointer based on user input
        //If user input is 2, and a=10, b=3 then below line will expand as "objFuncMap["Sub"](10, 3)"
        int ret = objFunMap[func](a, b);      
        cout<<ret<<endl;
    }
    return 0;
}

This way we have used function pointer in our actual company code. You may write 'n' number of function and call them using this method.

OUTPUT:

    Enter your choice( 1. Add 2. Sub 3. Multi) : 1
    Enter 2 no :2 4
    6
    Enter your choice( 1. Add 2. Sub 3. Multi) : 2
    Enter 2 no : 10 3
    7
    Enter your choice( 1. Add 2. Sub 3. Multi) : 3
    Enter 2 no : 3 6
    18
查看更多
疯言疯语
6楼-- · 2020-01-22 13:35

Well, I generally use them (professionally) in jump tables (see also this StackOverflow question).

Jump tables are commonly (but not exclusively) used in finite state machines to make them data driven. Instead of nested switch/case

  switch (state)
     case A:
       switch (event):
         case e1: ....
         case e2: ....
     case B:
       switch (event):
         case e3: ....
         case e1: ....

you can make a 2d array or function pointers and just call handleEvent[state][event]

查看更多
The star\"
7楼-- · 2020-01-22 13:36

Most examples boil down to callbacks: You call a function f() passing the address of another function g(), and f() calls g() for some specific task. If you pass f() the address of h() instead, then f() will call back h() instead.

Basically, this is a way to parametrize a function: Some part of its behavior is not hard-coded into f(), but into the callback function. Callers can make f() behave differently by passing different callback functions. A classic is qsort() from the C standard library that takes its sorting criterion as a pointer to a comparison function.

In C++, this is often done using function objects (also called functors). These are objects that overload the function call operator, so you can call them as if they were a function. Example:

class functor {
  public:
     void operator()(int i) {std::cout << "the answer is: " << i << '\n';}
};

functor f;
f(42);

The idea behind this is that, unlike a function pointer, a function object can carry not only an algorithm, but also data:

class functor {
  public:
     functor(const std::string& prompt) : prompt_(prompt) {}
     void operator()(int i) {std::cout << prompt_ << i << '\n';}
  private:
     std::string prompt_;
};

functor f("the answer is: ");
f(42);

Another advantage is that it is sometimes easier to inline calls to function objects than calls through function pointers. This is a reason why sorting in C++ is sometimes faster than sorting in C.

查看更多
登录 后发表回答