Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and medical aesthetics - Problems of Function Used as Function Parameter in C Language
Problems of Function Used as Function Parameter in C Language
Let me give you an example, so it will be much easier to understand.

Example: design a function func (); When calling, each time you implement a different function, you enter two parameters, a and b. When func () is called for the first time, the larger one of A and B is found, the smaller one is found for the second time, and the sum of A and B is found for the third time.

Description: format

(*p)()

Represents a pointer variable p that defines a function. In C language, this format is fixed. The former () indicates that p is a pointer variable that is combined with * first, while the latter () indicates that p points to a function. If the preceding () is written as

*p (), because () has a higher priority than *, which means that the p () function returns a pointer, and p itself is a function, not a pointer, and its meaning has completely changed.

For any function, the function name is the entry address (starting address) of the function, that is, the function name is an address. Starting from this address, the function occupies a memory location. So you can point to this function name with a pointer variable, which is equivalent to pointing to this function. So the following max, min and add functions are all an address. When calling separately, assign p = max, p = min and p = add respectively, that is, (*p)(x, y) is equal to max (x, y), min (x, y) and add (x, y) respectively.

The program is debugged under win-tc and Dev-c++.

# Including

& ltstdio.h & gt

# Including

& ltconio.h & gt

Internationalorganizations (same as international organizations)

Maximum value (integer

x,int

y)

{

return(x & gt; y? x:y);

}

Internationalorganizations (same as international organizations)

min(int

x,int

y)

{

return(x & lt; y? x:y);

}

Internationalorganizations (same as international organizations)

Add (integer

x,int

y)

{

return(x+y);

}

Internationalorganizations (same as international organizations)

func(int

x,int

y,int

(*p)())

/* Defines the pointer variable p, key 1*/

{int

Results;

Result =(*p)(x, y);

/* Call the corresponding function and give the function name or address to P, so that P points to the function, and the key is 2*/

printf("%d\n ",result);

}

Master ()

{

Internationalorganizations (same as international organizations)

Party A and Party B;

Printf ("Please

invest

two

integer

a

and

b:\ n ");

Scanf("%d%d ",&i, & b);

printf(" max = ");

func(a,b,max); /* is equivalent to assigning p=max*/

printf(" min = ");

func(a,b,min); /* is equivalent to assigning p=min*/

printf(" add = ");

func(a,b,add); /* is equivalent to assigning p=add*/

getch();

}