-
Notifications
You must be signed in to change notification settings - Fork 0
/
pointers_to_function.c
102 lines (72 loc) · 1.72 KB
/
pointers_to_function.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/* Program to illustrate the use
of pointers to function and dispatch
tables in C */
#include <stdio.h>
#include <string.h>
struct command {
char *name;
int (*function) (void);
};
int addentry();
int calcvals();
int delentry();
int listdb();
int quit();
int updentry();
// dispatch table
struct command dispatch[] = {
{ "add", addentry },
{ "calc", calcvals },
{ "delete", delentry },
{ "list", listdb },
{ "quit", quit },
{ "update", updentry }
};
/* function prototype */
int execute(char *,struct command *,int);
#define UNKNOWNCMD -1
#define QUITCMD 999
#define OKCMD 0
int execute(char *typedcmd,struct command dispatch[],int numcmds)
{
int i,fnresult=UNKNOWNCMD;
for(i=0;i < numcmds;i++) {
if(strcmp(typedcmd,dispatch[i].name) == 0) {
fnresult = (*dispatch[i].function) ();
break;
}}
return (fnresult);
}
void main() {
char buf[81];
int status;
int addentry (void),calcvals (void),delentry (void),listdb (void),
quit (void), updentry (void);
int entries = sizeof(dispatch) / sizeof (struct command);
do {
printf("\n Enter your command: ");
scanf("%s",buf);
status = execute(buf,dispatch,entries);
if(status == UNKNOWNCMD)
printf("Unknown command: %s\n",buf);
} while(status != QUITCMD);
}
/* dummy functions for testing */
int addentry (void) {
printf("in addentry\n");
return OKCMD; }
int calcvals (void) {
printf("in calcvals\n");
return OKCMD; }
int delentry (void) {
printf("in delentry\n");
return OKCMD; }
int listdb (void) {
printf("in listdb\n");
return OKCMD; }
int quit (void) {
printf("in quit\n");
return QUITCMD; }
int updentry (void) {
printf("in updentry\n");
return OKCMD; }