void main(void) { double opn1, opn2; /* working operands */ char s[LINE_SIZE]; /* input line buffer */ char opr; /* working operator */ char *p; /* buffer cursor */ printf("\nPrefix Form Evaluator"); printf("\n====================="); printf("\n\nInput --> "); gets(s); initial(); /* initial stack */ for (p = s; *p != '\0'; p++) /* for each character */ if (is_opr(*p)) /* is is an operator ? */ push_opr(*p); /* YES, push. */ else if (isdigit(*p)) { /* is it an operand ? */ opn2 = *p - '0'; /* YES, convert to double */ while (stack_top() == OPERAND) { opn1 = pop_opn(); /* for all of its */ opr = pop_opr(); /* buddy, compute */ opn2 = compute(opr, opn1, opn2); } push_opn(opn2); /* then push the result */ } printf("\nResult = %lf", pop_opn()); }
leaf *build(char *expr, hashtab *h) { lstack s; char opr; int i = -1, num; char str[MAX_STR]; leaf *l = NULL, *r = NULL, *tmp = NULL; lstack_init(&s, 1024); while (expr[++i]) { if (is_digit(expr[i])) { num = get_number(expr, &i); l = new_num_leaf(num, INT, NULL, NULL, -1); lpush(&s, l); } else if (is_opr(expr[i])) { lpop(&s, &r); lpop(&s, &l); //Optimization : reducing the amount of registers !! if ((expr[i] == '+' || expr[i] == '*') && l->typ == INT && r->typ != INT) tmp = l, l = r, r = tmp; l = new_num_leaf(expr[i], CHAR, l, r, get_reg_num(l, r)); lpush(&s, l); } else if (is_alpha(expr[i])) { get_string(expr, str, &i); if (search(h, str)) { lpop(&s, &r); r->reg = 1; //Premice to register allocation !!! l = new_str_leaf(str, FUNC, NULL, r, 1); lpush(&s, l); } else //If not a function then a variable identifier ! [extend the grammar] { l = new_str_leaf(str, VAR, NULL, NULL, -1); lpush(&s, l); } } } lstack_free(&s); return l; }