Personal implementation Examples:
Copy Code code as follows:
#include <stdio.h>
#include <string.h>
#define M 4
int add (int a, int b);
int sub (int a, int b);
int mul (int a, int b);
int div (int a, int b);
Int (*oper_func[]) (int, int) = {
Add, Sub, mul, div
};
Char oper_sequence[m][10] = {
"Add", "sub", "Mul", "div"
};
int main ()
{
Char oper[10];
int seq;
int a,b;
int result;
int i;
printf ("Operator:");
scanf ("%s", Oper);
printf ("A:");
scanf ("%d", &a);
printf ("B:");
scanf ("%d", &b);
for (i=0; i<m; i++)
{
if (strncmp (Oper_sequence[i], oper, 3) = = 0)
seq = i;
}
result = Oper_func[seq] (A, b);
printf ("Result was%d/n", result);
return 0;
}
int add (int a, int b)
{
return a+b;
}
int sub (int a, int b)
{
return a-b;
}
int mul (int a, int b)
{
return a*b;
}
int div (int a, int b)
{
return a/b;
}
<<c and Pointers >> Original:
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.