#include <stdio.h>
enum response_type {DUMP,SECOND_CHANCE,MARRIAGE};
typedef struct{
char *name;
enum response_type type;
} response;
void dump(response r)
{
printf("Dear %s,\n",r.name);
puts("Unfortunately your last date contacted us to");
puts("say that they will not be seeing you again");
}
void second_chance(response r)
{
printf("Dear %s,\n",r.name);
puts("Good news:you last date has asked us to");
puts("arrange another meeting. please call ASAP.");
}
void marriage(response r)
{
printf("Dear %s,\n",r.name);
puts("Congratulations! Your last date has contacted");
puts("us with a propisal of marriage.");
}
int main()
{
response r[] = {
{"Mike",DUMP},{"Luis",SECOND_CHANCE},
{"Matt",SECOND_CHANCE},{"William",MARRIAGE}
};
int i;
for(i = 0; i < 4; i++){
switch(r[i].type){
case DUMP:
dump(r[i]);
break;
case SECOND_CHANCE:
second_chance(r[i]);
break;
default:
marriage(r[i]);
}
}
return 0;
}
- 函数
dump()
、second()
、amrriage()
有着相同的返回值类型和心鬼头鬼脑的参数类型和列表。 - 如果想要在数组中保存函数,就要告诉编译器函数的具体特征。因此要是使用复杂的语法。
- 在C语言中,创建枚举时会为每一个符号分配一个从
0
开始的数字,一次DUMP == 0, SECOND_CHANCE == !, MARRIGE ==2
。
replies[SECOND_CHANCE] == second_chance
因此代码可以改成:
void (*replies[])(response) = {dump,second_chance,marriage};
int main()
{
response r[] = {
{"Mike",DUMP}, {"Luis",SECOND_CHANCE},
{"Matt",SECOND_CHANCE},{"William",MARRIAGE}};
int i;
for(i = 0; i < 4; i++){
(replies[r[i].type])(r[i]);
}
return 0;
}
函数指针数组2.jpg
网友评论