01: // example of selection of a function using an array of func pointers
02: #include<stdio.h>
03: #include<stdlib.h>
04: 
05: float sum(float a, float b)
06: {
07:   return a + b;
08: }
09: 
10: float sub(float a, float b)
11: {
12:   return a - b;
13: }
14: 
15: float mult(float a, float b)
16: {
17:   return a * b;
18: }
19: 
20: float divi(float a, float b)
21: {
22:   return a / b;
23: }
24: 
25: 
26: 
27: 
28: int main(int argc, char **argv){
29: 
30:   float op1, op2;
31:   printf("Enter two numbers: ");
32:   scanf("%f%f", &op1, &op2);
33: 
34:   int oper;
35:   printf("Enter your choiche (0 = sum, 1 = sub, 2 = mult, 3 = div): ");
36:   scanf("%d", &oper);
37: 
38:   /* without func pointers
39:   float res;
40:   switch(oper)
41:   {
42:     case 0:
43:       res = sum(op1, op2);
44:       break;
45:     case 1:
46:       res = sub(op1, op2);
47:       break;
48:     case 2:
49:       res = mult(op1, op2);
50:       break;
51:     case 3:
52:       res = divi(op1, op2);
53:       break;
54:   }
55:   */
56: 
57:   // definition of an array of func pointers
58:   float (*math[])(float, float) = {sum, sub, mult, divi};
59: 
60:   printf("The result is %g\n", math[oper](op1, op2));
61: 
62: 
63: 
64:   return 0;
65: }
66: 
67: 


Se avete commenti o osservaƶioni su questa pagina
mandate un messaggio di posta elettronica a bertoƶƶi@ce.unipr.it