baum

changeset 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 7adeee76ce3e
children f5f06d6f62b3
files actions.c
diffstat 1 files changed, 22 insertions(+), 22 deletions(-) [+]
line diff
     1.1 --- a/actions.c	Sun Mar 16 20:11:02 2008 +0100
     1.2 +++ b/actions.c	Wed Jun 25 09:20:16 2008 +0200
     1.3 @@ -11,9 +11,26 @@
     1.4  unsigned char action_if(struct Node* node);
     1.5  unsigned char action_while(struct Node* node);
     1.6  
     1.7 +struct action {
     1.8 +	char* name;
     1.9 +	unsigned char (*func)(struct Node* node);
    1.10 +};
    1.11 +
    1.12 +struct action actions[] = {
    1.13 +	{"print", action_print},
    1.14 +	{"sum", action_sum},
    1.15 +	{"number", action_number},
    1.16 +	{"create", action_create},
    1.17 +	{"times", action_times},
    1.18 +	{"if", action_if},
    1.19 +	{"while", action_while},
    1.20 +};
    1.21 +
    1.22  
    1.23  
    1.24  unsigned char action(struct Node* node) {
    1.25 +	int i;
    1.26 +
    1.27  	if (node == NULL) {
    1.28  		if (option_verbose) {
    1.29  			fprintf(stderr, "warning: action of non existing node\n");
    1.30 @@ -21,31 +38,14 @@
    1.31  		return 0;
    1.32  	}
    1.33  
    1.34 -	if (strcmp(node->name, "print") == 0) {
    1.35 -		return action_print(node);
    1.36 +	for (i = 0; i < (sizeof(actions)/sizeof(actions[0])); i++) {
    1.37 +		if (strcmp(actions[i].name, node->name) == 0) {
    1.38 +			return (actions[i].func)(node);
    1.39 +		}
    1.40 +	}
    1.41  
    1.42 -	} else if (strcmp(node->name, "sum") == 0) {
    1.43 -		return action_sum(node);
    1.44 -
    1.45 -	} else if (strcmp(node->name, "number") == 0) {
    1.46 -		return action_number(node);
    1.47 -
    1.48 -	} else if (strcmp(node->name, "create") == 0) {
    1.49 -		return action_create(node);
    1.50 -
    1.51 -	} else if (strcmp(node->name, "times") == 0) {
    1.52 -		return action_times(node);
    1.53 -
    1.54 -	} else if (strcmp(node->name, "if") == 0) {
    1.55 -		return action_if(node);
    1.56 -
    1.57 -	} else if (strcmp(node->name, "while") == 0) {
    1.58 -		return action_while(node);
    1.59 -
    1.60 -	} else {
    1.61  		fprintf(stderr, "unknown kind of node\n");
    1.62  		exit(4);
    1.63 -	}
    1.64  }
    1.65  
    1.66