Application of language function pointer c

Application of language function pointer c

1, function pointers and function pointers

  Before you begin using a function pointer, we need two concepts namely: function pointers and function pointers clear.

Function pointer, a function indicating this, but the return value is a pointer type, syntax is:

    * Function name Name Type A (parameter list);

When you call him, we can use

    Variable name = name type function name * A (parameter list);

Function pointer, indicating that this is a pointer, but a pointer to a function, syntax is:

    Type the name (function name * fun) (parameter list);

 

When you call him, we can use

 For example, there is a function

              Type the name of the function name B (parameter list);

              We can use

The first usage

             fun=&B;

              (* Fun) (parameter list); 

The second usage

    fun=B;

    (* Fun) (parameter list);

These two statements to call the function B. This view with the pointer to the function code further more, but in large programs, if the parameter type of the function A and the function B, and the case where the return value types are the same, can be unified with the pointer function fun to call, write clean code.

2, code examples

#include<stdio.h>

int add(int a, int b) {
	return a+b;
}

int sub(int a, int b) {
	return a-b;
}

typedef int (*fun)(int a, int b);

fun globalFun[2]=
{
	[0] = add,
	[1] = sub,
};

int main() {
	int first = 5;
	int second = 10;
	printf("%d\n", globalFun[0](first, second));
	printf("%d\n", globalFun[1](first, second));
	return 0;
}

  

 

Guess you like

Origin www.cnblogs.com/grglym/p/11493891.html