K and R Exercise 5-10
Write the program expr, which evaluates a reverse Polish expression from the command line, where each operator or operand is a separate argument.
For example,
expr 2 3 4 + *
evaluates
2 * (3+4)
#include <stdio.h>
#include "expression_parser.h"
int parse_polish(int size, char *expression[])
{
char *entry;
int temp1, temp2;
if (expression[1] && ((isdigit(*expression[1]) &&
isdigit(*expression[2])))) {
stack_init(&size, expression);
expression++;
for ( ; *expression; expression++) {
if (isdigit(*(entry = *expression)))
push(atoi(entry));
else {
switch (*entry) {
case '+':
push(pop() + pop());
break;
case '-':
temp1 = pop();
temp2 = pop();
push(temp1 - temp2);
break;
case '*':
push(pop() * pop());
break;
case '/':
temp1 = pop();
temp2 = pop();
if (!(temp2))
return -1;
else
push(temp1 / temp2);
break;
default:
return -1;
}
}
}
return pop();
} else
return -1;
}