Function pointers and Applications

Source: Internet
Author: User

Let's take a look at the following statement:

Int F (INT );

Int(* PF) (INT) = & F; // & operator optional; because the function name is always used by the compiler

                           // Convert to a function pointer;

Int ans;

Ans = f (25 );

Ans = (* PF) (25 );

Ans = PF (25); // indirect access operations are not required because the compiler needs a function pointer;

**************************************** **************************************** **

The two most common purposes are to pass the function pointer as a parameter to the function and to convert the table!

1. Callback Function

Here is a simple function used to find a value in a single-chain table. Its parameter is

The pointer of the first node of the linked list and the value to be searched.

Node * search_list (node * node, int const value)

{ While (node! = NULL)

 {  If (node-> value = value)

               Break;

      Node = node-> link;

  }

   Return node;

}

     This function looks quite simple, but it only applies to linked lists with integer values.

You have to write another function for searching in the string linked list.

Some codes are the same, but the type of the second parameter and the comparison method of the node value are different.

      A more common method is to find a function that is irrelevant to the type so that it can be used for any type of value.

The linked list, we must modify the two aspects of the function to make it irrelevant to the type. First, we must change

The execution method of the comparison, so that the function can compare any type of value. This object sounds like

No. If you write a statement to compare integer values, how can it be used for other types, such as strings?

? The solution is to use the function pointer. The caller writes a function to compare two values and then

Pass a pointer pointing to this function as a parameter to the lookup function, and then find the function to call this

To compare the values. Using this method, any type of values can be compared.

      The second aspect that we must modify is to pass a pointer to the value to the function instead of itself.

The function is a void * parameter used to receive this parameter, and then the pointer pointing to this value is passed to the comparison

Function. This modification allows the string and array objects to be used. Strings and arrays cannot be passed as parameters.

Pass to the function, but the pointer to them is acceptable.

     A function using this technique is called a callback function.

The needle is passed as a parameter to other functions, and the latter calls back the user's function. At any time, if

The function must be able to execute different types of work or execution at different times, which can only be defined by the function caller.

You can use this technique. Many window systems use callback functions to connect multiple actions,

Such as dragging the mouse and clicking the button to specify a specific function in the user program.

     We cannot compile an accurate prototype for the callback function in this context, because we

I don't know the type of the value to be compared. In fact, we need to find the type of value that the function can act on,

The solution to this problem is to declare the parameter type as "Void *", indicating "one pointing to the unknown type

Pointer ".

   

# Include

# Include "node. H"

Node * search_list (node * node, voidConst * value,

                 INT (* compare) (void const *, void const *)) // Function declaration;

{   While (Node! = NULL)

         {    If (compare (& node-> value, value) = 0) Break;

                 Node = node-> link;

          }

       Return node;

}

     Note that although the function does not modify any node to which the parameter node points, node does not declare

Const. If node is declared as const, the function has to return a const result, which limits

By calling the program, it cannot modify the node found by the search function.

     When searching in a specific linked list, you need to compile an appropriate comparison function and

The pointer pointing to the function and the pointer pointing to the value to be searched are passed to the lookup function. For example, the following

Is a comparison function used to search in an integer linked list.

Int compare_ints (void const * a, void const * B)

{

        If (* (int *) A = * (int *) B)   Return 0;

         Else   Return 1;

}

      This function will be used as follows:

Desired_node = search_list (root, & desired_value, compare_ints );

2. conversion table (jump table)

   It is best to use an example to explain the transfer table. The following code snippet is taken from a program for implementation.

A pocket calculator. The other part of the program has read two numbers (OP1 and OP2) and one

Operator ). The following code tests the operators and determines which function to call.

Switch)

{

Case Add: Result = add (OP1, OP2); break;

Case Sub:  Result = sub (OP1, OP2); break;

Case Mul:  Result = MUL (OP1, OP2); break;

Case Div:   Result = div (OP1, OP2); break;

......}

     For a novel calculator with hundreds of operators, this switch statement will be very long.

      Why do I need to call a function to perform these operations? Separate the specific operation code from the selected operation code.

Is a good design solution. More complex operations will certainly be implemented using independent functions, because

They may be long. However, even a simple operation may have side effects, such as saving

A constant value is used for subsequent operations.

        To use the switch statement, the code of the operator must be an integer. If they start from scratch

Continuous integers. We can use a conversion table to implement the same task. A conversion table is a function pointer.

Array.

     Two steps are required to create a conversion table. First, declare and initialize a function pointer array. Unique

Note that the prototype of these functions appears before the declaration of the array.

Double add (double, double );

Double sub (double, double );

Double MUL (double, double );

Double Div (double, double );

......

Double (* oper_func []) (double, double) = {

Add, sub, Mul, Div,

......};

     The correct sequence of function names in the initialization list depends on

Integer code. This example assumes that add is 0, sub is 1, mul is 2, and so on.

     The second step is to replace the previous switch statement with the following statement!

Result = oper_func [condition] (OP1, OP2 );

    The handler selects the correct function pointer from the array, and the function call operator will execute this function.

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.