C and pointer function pointer __ function

Source: Internet
Author: User
Tags mul

Excerpt from "C and pointers"

Two applications of function pointers:

I. callback function, the approximate template is as follows: int fun (int a,int (*com) (void const *a,void const *b)); COM here is a callback function, that is, the user needs to use the fun function, the need to pass a pointer over the function, The function that is pointed to is written by the user.

When to use a callback function: The written function must be able to perform different types of work at different times or perform work that can only be defined by the function caller, and you can use this technique.

Note: The callback function passes through a function pointer, not the function itself. This function argument must be a void const *. Inside a function you have to make sure that you convert to the correct type. If you want to be compatible with some of the system's functions, So equality returns 0. Unequal returns 1. This is mostly like a string, which can represent 3 situations. 0: Equal,-1: The first small. 1 (or just a book larger than 0): the first big.

Ii. Transfer table: That is, each element of an array is a function pointer. Then the corresponding function is accessed by subscript. Double (*oper_func []) (double,double) ={add,sub,mul,div};

Transfer table to be very careful of the subscript overflow, a little overflow can be very difficult to debug.

callback function
Here's a simple function that looks up a value in a single linked list, and its argument is a pointer to the first node in the list and the value that needs to be found.
node* search_list (node* node,int const value)
{
while (Node!=null)
{
if (node->value==value) break;
node=node->link;
}
return node;
}
This function looks pretty simple, but it only applies to lists of values that are integers, and if you need to find them in a string list, you have to write a function that is the same as most of the code on the above function. Just the type of the second parameter and the comparison method of the node value are different. A more general approach is to find functions that are not related to a type, so that it can be used for lists of values of any type, and we have to modify the two aspects of the function to make it irrelevant to the type.
First we have to change the way the comparison is performed so that the function can compare the values of any type. This goal sounds impossible, if you write statements to compare integer values, how can it be used for other types such as String comparisons? The solution is to use the function pointer, the caller writes a function, Used to compare two values, and then pass a pointer to the function as a parameter to the lookup function. Then the lookup function calls this function to perform a comparison of values, using this method, Any type of value can be compared. The second aspect that we have to modify is to pass a pointer to a function instead of itself. A function is passed a void * parameter, which is used to receive this parameter, and then the pointer to the value is then transmitted to the comparison function, which makes the string and array objects available for use, strings and arrays cannot be passed as arguments to functions, but pointers to them can.
Functions that use this technique are called "Callback functions" (callback function), because the user passes a function pointer to another function as a parameter, which will "callback" the user's function. Any time, You can use this technique if you write a function that must be able to perform different types of work at different times or perform work that can only be defined by the function caller. Many window systems use callback functions to connect multiple actions, such as dragging the mouse and clicking on the button to specify a specific function in the user program. We cannot write a precise prototype for the callback function in this context, because we do not know the type of the value being compared. In fact, we need to find a function that works on any type of value, The solution to this dilemma is to declare the parameter type as "void *", which means "a pointer to an unknown type."


/*** a function that finds a specified value in a single list, and its argument is a pointer to the first node of the list
* * Pointer, a pointer to the value we need to find, and a function pointer to the function that it points to
* * is used to compare the values of types stored in this list.
*/
#include "node.h"
node* search_list (Node *node,void const *value, int (*compare) (void const*,void const*))//function declaration;
{
while (Node!=null)
{
if (compare (&node->value,value) ==0) break;
node=node->link;
}
return node;
}
Also note that although the function does not modify any of the nodes that the parameter node points to, node is not declared const. If node is declared const, the function has to return a const result, which limits the calling program, and it cannot modify the node found by the lookup function.
When looking in a particular list, the user needs to write an appropriate comparison function and pass the pointer to the function and the pointer to the value that needs to be found to the lookup function.
For example, here is a comparison function that is used to find 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);

Convert table (jump table)
The transfer table is best explained by an example. The following code snippet is taken from a program that implements a pocket calculator. Other parts of the program have been read into two numbers (OP1 and OP2) and one operator (OPER). The following code tests the operator and finally decides which function to call.
Switch (OPER)
{
Case Add:result=add (OP1,OP2);
Case Sub:result=sub (OP1,OP2);
Case Mul:result=mul (OP1,OP2);
Case Div:result=div (OP1,OP2);
......
}

For a novel calculator with hundreds of operators, this switch statement will be very long. Why do you call functions to perform these operations? It is a good design scheme to separate the code of operation and selection. More complex operations will certainly be implemented as separate functions, because they may be long in length. But even simple operations can have side effects, such as saving a constant value for later operations.
In order to use the switch statement, the code that represents the operator must be an integer. If they are consecutive integers from zero, we can use the conversion table to accomplish the same task. A conversion table is an array of function pointers.
Creating a conversion table requires two steps. First, declare and initialize an array of function pointers. The only thing to be aware of is to make sure that the prototypes of these functions appear before the declaration of this 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 order of each function name in the initialization list depends on the integer code used by the program to represent each operator. This example assumes that add is 0,sub is 1,mul is 2, then so on.
The second step is to replace the previous entire switch statement with the following statement.
Result=oper_func[oper] (OP1,OP2);
Oper selects the correct function pointer from the array, and the function call operator executes the function.

Related Article

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.