Evaluate a postfix expression.
#include <ctype.h>
/* single-digit operands; returns 0 and sets *ok = 0 on error */
long eval_postfix(const char *s, int *ok)
{
long st[64]; int top = 0;
*ok = 1;
for (; *s; s++) {
if (isdigit((unsigned char)*s)) { st[top++] = *s - '0'; continue; }
if (*s == ' ') continue;
if (top < 2) { *ok = 0; return 0; }
long b = st[--top], a = st[--top]; /* order matters for - and / */
switch (*s) {
case '+': st[top++] = a + b; break;
case '-': st[top++] = a - b; break;
case '*': st[top++] = a * b; break;
case '/': if (b == 0) { *ok = 0; return 0; } st[top++] = a / b; break;
default: *ok = 0; return 0;
}
}
if (top != 1) { *ok = 0; return 0; }
return st[0];
}
/* "231*+9-" -> 2 + 3*1 - 9 = -4 */
Points: push operands, pop two for each operator (the first popped is the right operand), push the result; at the end exactly one value must remain. Check stack underflow, division by zero and leftover values.