函数指针基本用法

1.基本用法
#include <stdio.h>

int add(int x, int y) {return(x + y);}
int sub(int x, int y) {return(x - y);}
int mul(int x, int y) {return(x * y);}
int div(int x, int y) {return(x / y);}

int main(void)
{
  int (*pf)(int, int);

  pf = add;
  printf("%dn", pf(9, 3)); /* 12 */
  
  pf = sub;
  printf("%dn", pf(9, 3)); /* 6 */
  
  pf = mul;
  printf("%dn", pf(9, 3)); /* 27 */
  
  pf = div;
  printf("%dn", pf(9, 3)); /* 3 */
  
  getchar();
  return 0;
}


2.函数指针数组
#include <stdio.h>

int add(int x, int y) {return(x + y);}
int sub(int x, int y) {return(x - y);}
int mul(int x, int y) {return(x * y);}
int div(int x, int y) {return(x / y);}

int main(void)
{
  int (*pf[4])(int, int) = {add, sub, mul, div};

  printf("%dn", pf[0](9, 3)); /* 12 */
  printf("%dn", pf[1](9, 3)); /* 6 */
  printf("%dn", pf[2](9, 3)); /* 27 */
  printf("%dn", pf[3](9, 3)); /* 3 */
  
  getchar();
  return 0;
}


3.函数指针做参数
#include <stdio.h>

int add(int x, int y) {return(x + y);}
int sub(int x, int y) {return(x - y);}
int mul(int x, int y) {return(x * y);}
int div(int x, int y) {return(x / y);}

int math(int(*pfun)(int, int), int x, int y) {
  return pfun(x, y);
}

int main(void)
{
  printf("%dn", math(add, 9, 3)); /* 12 */
  printf("%dn", math(sub, 9, 3)); /* 6 */
  printf("%dn", math(mul, 9, 3)); /* 27 */
  printf("%dn", math(div, 9, 3)); /* 3 */
  
  getchar();
  return 0;
}

你可能感兴趣的:(C++,c,C#)