What are function pointers used for, and how would I use them?

前端 未结 9 2330
野趣味
野趣味 2020-11-29 06:51

I understand I can use pointers for functions.

Can someone explain why one would use them, and how? Short example code would be very helpful to me.

9条回答
  •  暖寄归人
    2020-11-29 07:19

    You use a function pointer when you need to give a callback method. One of the classic example is to register signal handlers - which function will be called when your program gets SIGTERM (Ctrl-C)

    Here is another example:

    // The four arithmetic operations ... one of these functions is selected
    // at runtime with a switch or a function pointer
    float Plus    (float a, float b) { return a+b; }
    float Minus   (float a, float b) { return a-b; }
    float Multiply(float a, float b) { return a*b; }
    float Divide  (float a, float b) { return a/b; }
    
    // Solution with a switch-statement -  specifies which operation to execute
    void Switch(float a, float b, char opCode)
    {
       float result;
    
       // execute operation
       switch(opCode)
       {
          case '+' : result = Plus     (a, b); break;
          case '-' : result = Minus    (a, b); break;
          case '*' : result = Multiply (a, b); break;
          case '/' : result = Divide   (a, b); break;
       }
    
       cout << "Switch: 2+5=" << result << endl;         // display result
    }  
    
    // Solution with a function pointer -  is a function pointer and points to
    // a function which takes two floats and returns a float. The function pointer
    // "specifies" which operation shall be executed.
    void Switch_With_Function_Pointer(float a, float b, float (*pt2Func)(float, float))
    {
       float result = pt2Func(a, b);    // call using function pointer
    
       cout << "Switch replaced by function pointer: 2-5=";  // display result
       cout << result << endl;
    }
    

    You can learn more about function pointers here http://www.newty.de/fpt/index.html

    If you are more familiar with object-oriented languages, you can think of it as C's way to implement the strategy design pattern.

提交回复
热议问题