comparison actions.c @ 57:21ff1783f640

using function pointers now, instead of a large if-else
author meillo@marmaro.de
date Wed, 25 Jun 2008 09:20:16 +0200
parents 6279e5b14d9e
children
comparison
equal deleted inserted replaced
56:7adeee76ce3e 57:21ff1783f640
9 unsigned char action_create(struct Node* node); 9 unsigned char action_create(struct Node* node);
10 unsigned char action_times(struct Node* node); 10 unsigned char action_times(struct Node* node);
11 unsigned char action_if(struct Node* node); 11 unsigned char action_if(struct Node* node);
12 unsigned char action_while(struct Node* node); 12 unsigned char action_while(struct Node* node);
13 13
14 struct action {
15 char* name;
16 unsigned char (*func)(struct Node* node);
17 };
18
19 struct action actions[] = {
20 {"print", action_print},
21 {"sum", action_sum},
22 {"number", action_number},
23 {"create", action_create},
24 {"times", action_times},
25 {"if", action_if},
26 {"while", action_while},
27 };
28
14 29
15 30
16 unsigned char action(struct Node* node) { 31 unsigned char action(struct Node* node) {
32 int i;
33
17 if (node == NULL) { 34 if (node == NULL) {
18 if (option_verbose) { 35 if (option_verbose) {
19 fprintf(stderr, "warning: action of non existing node\n"); 36 fprintf(stderr, "warning: action of non existing node\n");
20 } 37 }
21 return 0; 38 return 0;
22 } 39 }
23 40
24 if (strcmp(node->name, "print") == 0) { 41 for (i = 0; i < (sizeof(actions)/sizeof(actions[0])); i++) {
25 return action_print(node); 42 if (strcmp(actions[i].name, node->name) == 0) {
43 return (actions[i].func)(node);
44 }
45 }
26 46
27 } else if (strcmp(node->name, "sum") == 0) {
28 return action_sum(node);
29
30 } else if (strcmp(node->name, "number") == 0) {
31 return action_number(node);
32
33 } else if (strcmp(node->name, "create") == 0) {
34 return action_create(node);
35
36 } else if (strcmp(node->name, "times") == 0) {
37 return action_times(node);
38
39 } else if (strcmp(node->name, "if") == 0) {
40 return action_if(node);
41
42 } else if (strcmp(node->name, "while") == 0) {
43 return action_while(node);
44
45 } else {
46 fprintf(stderr, "unknown kind of node\n"); 47 fprintf(stderr, "unknown kind of node\n");
47 exit(4); 48 exit(4);
48 }
49 } 49 }
50 50
51 51
52 52
53 unsigned char action_print(struct Node* node) { 53 unsigned char action_print(struct Node* node) {