跳转表实例(二)

来源:互联网 发布:linux mount phyaddr 编辑:程序博客网 时间:2024/06/15 07:03
#include<stdio.h>      #include<string.h>    #include<stdlib.h>#define ERROR_SUCCESS0#define ERROR_FAILED-1#define MENU_NUM_MAX5typedef enum menu{MENU_UNSPEC,MENU_ADD,MENU_SUB,MENU_EXIT,MENU_MAX}MENU_E;static void DisplayMenu(void){printf("\r----Menu----\n\\r1.Add\n\\r2.Sub\n\\r3.Exit\n\\r------------\n");}static int GetChoice(MENU_E *choice){printf("Please input your choice:\n");scanf("%d", choice);if((*choice <= MENU_UNSPEC) || (*choice >= MENU_MAX)){return ERROR_FAILED;}return ERROR_SUCCESS;}static int Add(void){int augend = 0;//被加数int addend = 0;//加数printf("请输入被加数、加数:\n");scanf("%d, %d", &augend, &addend);return (augend + addend);}static int Sub(void){int subtrahend = 0;//被减数int subtractor = 0;//减数printf("请输入被减数、减数:\n");scanf("%d, %d", &subtrahend, &subtractor);return (subtrahend - subtractor);}static int Exit(void){return ERROR_SUCCESS;}/* 函数指针。该函数参数为空,返回值为整型。 */typedef int (* OPERATE_PF)(void);typedef struct cmd_operate{MENU_E cmd;OPERATE_PF func;}CMD_OPERATE_S;static CMD_OPERATE_S operate[MENU_NUM_MAX] = {{MENU_UNSPEC, NULL},{MENU_ADD, Add},{MENU_SUB, Sub},{MENU_EXIT, Exit},{MENU_MAX, NULL}};void main(void){OPERATE_PF pfFunc = NULL;MENU_E choice = MENU_UNSPEC;int errCode = ERROR_SUCCESS;int result = 0;do{DisplayMenu();errCode = GetChoice(&choice);if(ERROR_SUCCESS == errCode){pfFunc = operate[choice].func;result = pfFunc();if(MENU_EXIT != choice){printf("The result is : %d\n", result);}}if(ERROR_SUCCESS != errCode){printf("Input parameter invalid.\n");}}while(MENU_EXIT != choice);return;}

原创粉丝点击