In use in typedef, the most troublesome is the pointer to the function. If you don't have the following functions, you know the definition of the expression below and how to use it?
INT (* s_calc_func (char OP)) (int, int);
Please see the program below, there is a more detailed explanation // definition four functions
INT Add (int, int);
int SUB (int, int);
INT MUL (int, int);
INT DIV (int, int);
/ / Define a pointer to this type of function
Typedef int (* fp_calc) (int, int);
// I will not introduce it first. Can you understand the content of the next line?
INT (* s_calc_func (char OP)) (int, int);
// The content of the next line is exactly the same as the previous line.
/ / Define a function CALC_FUNC, which returns a pointer to the corresponding calculation function based on the operation character OP
FP_CALC CALC_FUNC (CHAR OP);
[Fp_calc is actually a new type of data, which is pointing
Pointer type of function in the form of the above function]
/ / Return the corresponding calculation result value according to OP
Int Calc (int A, int B, char OP);
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 B? A / B: -1;
}
// This function is the same as the next function job and the mode of calling.
/ / The parameter is OP, not the last two places
Int (* s_calc_func (char OP)) (int, int)
{
Return Calc_Func (OP);
}
FP_CALC CALC_FUNC (CHAR OP)
{
Switch (OP)
{
Case ' ': Return ADD;
Case '-': Return Sub;
Case '*': return MUL;
Case '/': Return DIV;
DEFAULT:
Return NULL;
}
Return NULL;
}
Int Calc (int A, int B, char OP)
{
FP_CALC FP = CALC_FUNC (OP); // The following is a similar direct definition pointing function pointer variable
// The following line is not using typedef to implement a pointer to the function, trouble!
INT (* S_FP) (INT, INT) = S_Calc_Func (OP);
// assert (fp == s_fp); // can assert that these two are equal
IF (fp) Return FP (A, B);
Else Return -1;
}
Void test_fun ()
{
INT A = 100, b = 20;
Printf ("Calc (% D,% D,% C) =% D / N", A, B, ' ', CALC (A, B, ' '));
Printf ("Calc (% D,% D,% C) =% D / N", A, B, '-', CALC (A, B, '-'));
Printf ("Calc (% D,% D,% C) =% D / N", A, B, '*', CALC (A, B, '*')); Printf ("Calc (% D,%) D,% C) =% D / N ", A, B, '/', CALC (A, B, '/'));
}
operation result
Calc (100, 20, ) = 120
Calc (100, 20, -) = 80
Calc (100, 20, *) = 2000
Calc (100, 20, /) = 5