In the use of typedef, the most troublesome thing is to point to the function pointer. Without the following function, do you know the definition of the following expression and how to use it?
Int (*
S_calc_func(
CharOP ))(
Int,
Int); If you do not know, see the following Program , Which provides detailed descriptions.
//
Define four functions
Int
Add (
Int ,
Int );
Int
Sub (
Int ,
Int );
Int
Mul (
Int ,
Int );
Int
Div (
Int ,
Int );
//
Define 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(
CharOP ))(
Int,
Int);
//
The content of the next line is exactly the same as that of the previous line,
//
Define a function
Calc_func
, Which is based on the operating characters
OP
Returns the pointer to the corresponding computing function.
Fp_calc Calc_func (
Char OP );
//
According
OP
Returns the calculated result value.
Int Calc (
Int A,
Int B,
Char OP );
Int Add (
Int A,
Int B ){
ReturnA + B; }
Int Sub (
Int A,
Int B ){
ReturnA-B; }
Int Mul (
Int A,
Int B ){
ReturnA * B; }
Int Div (
Int A,
Int B ){
ReturnB? A/B:-1; }
//
This function is used exactly the same as the next function job and call method,
//
The parameter is
OP
Instead of the last two integers.
Int (* S_calc_func (
Char OP ))(
Int ,
Int ){
ReturnCalc_func (OP ); }
Fp_calc Calc_func (
Char OP ){
Switch(OP) {
Case'+ ':
ReturnAdd;
Case'-':
ReturnSub;
Case'*':
ReturnMul;
Case'/':
ReturnDiv;
Default:
Return
Null; }
Return
Null; }
Int Calc (
Int A,
Int B,
Char OP ){
Fp_calcFp = calc_func (OP );
//
The following is a similar direct definition of the pointer variable to the function.
//
The following line is unnecessary.
Typedef
To implement the pointer to the function!
Int(* S_fp )(
Int,
Int) = S_calc_func (OP );
//Assert(FP = s_fp );//
It can be asserted that the two are equal.
If(FP)
ReturnFP (A, B );
Else
Return-1; }
Void Test_fun (){
IntA = 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, '/')); }
Running result Calc (100, 20, +) = 120 Calc (100, 20,-) = 80 Calc (100, 20, *) = 2000 Calc (100, 20,/) = 5