範例一
#include <stdio.h>
#include <stdlib.h>
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 divv (int a, int b)
{ return a/b;
}
int main (void)
{
int c=20,d=2;
int e;
int (*test)(int c, int d)=&add; //函式指標, 預設值為 add
char key;
printf("Press +,-,*,/ for add, sub, mul, div\n");
key=getch();
switch(key)
{
case '+':
test=add; break;
case '-':
test=sub; break;
case '*':
test=mul; break;
case '/':
test=divv; break;
}
e=test(c,d);
printf("%d\n",e);
system("pause");
}
範例二
#include <stdio.h>
#include <stdlib.h>
#define ARRAY_SIZE(A) (sizeof(A)/sizeof(A[0]))
typedef struct _BtnAction *BtnAction;
typedef struct BtnAction
{
char key;
int (*func)(int, int);
}
_BtnAction;
int BtnAdd(int a, int b)
{
return a+b;
}
int BtnSub(int a, int b)
{
int tmp;
if (b > a)
{
tmp=a;
a=b;
b=tmp;
}
printf("a-b=%d\n", a-b);
return a-b;
}
_BtnAction BtnAct[]=
{
{ '+', BtnAdd},
{ '-', BtnSub}
};
int main (void)
{
char key;
int i=0;
int ret=0;
printf("Press +,-,*,/ for add, sub, mul, div\n");
key=getchar();
for (i=0; i<ARRAY_SIZE(BtnAct); i++)
{
if ( key == BtnAct[i].key)
{
ret=BtnAct[i].func(5, 3);
break;
}
}
printf("ret=%d\n", ret);
return 0;
}
沒有留言:
張貼留言