blob: 66457543e2c823b54e67283d95032088445bd900 (
plain)
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
|
/*
** FPSELECT.C - Demonstrates using function pointers in lieu of switches
*/
#include <stdlib.h> /* for NULL */
/* Declare your functions here */
char *cpfunc1(int);
char *cpfunc2(int);
char *cpfunc3(int);
void vfunc1(void);
void vfunc2(void);
void vfunc3(void);
void vfunc4(void);
/*
** Old ways using switch statements
*/
char *oldcpswitch(int select, int arg)
{
switch (select)
{
case 1:
return cpfunc1(arg);
case 2:
return cpfunc2(arg);
case 3:
return cpfunc3(arg);
default:
return NULL;
}
}
void oldvswitch(int select)
{
switch (select)
{
case 1:
vfunc1();
break;
case 2:
vfunc2();
break;
case 3:
vfunc3();
break;
case 4:
vfunc4();
break;
}
}
/*
** Using function pointers
*/
char *newcpswitch(int select, int arg)
{
char *(*cpfunc[3])(int) = { cpfunc1, cpfunc2, cpfunc3 };
if (select < 1 || select > 3)
return NULL;
return (*cpfunc[select-1])(arg);
}
void newvswitch(int select)
{
void (*vfunc[4])(void) = { vfunc1, vfunc2, vfunc3, vfunc4 };
if (select > 0 && select < 5)
(*vfunc[select-1])();
}
|