People write infix (A+B*C); computers evaluate postfix (ABC*+) more easily because it needs no parentheses or precedence rules. The shunting-yard idea: operands go straight to the output; operators wait on a stack and pop when an operator of equal or higher precedence arrives; ( is pushed, and ) pops until (.
Remember
operand -> output
'(' -> push
')' -> pop to output until '('
operator -> pop while prec(top) >= prec(op); push op
end -> pop everything
Reference
Cheat Sheet
Keep these facts handy while you work with Expression Conversion in C.
Topic
Detail
Precedence
*/ over +-
Associativity
Left to right pops equals
Parentheses
Push (, pop at )
Time
O(n)
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Expression Evaluation.
Example 1 — Convert three expressions
Single-letter operands, four operators, parentheses.
C
#include <ctype.h>
#include <stdio.h>
static int prec(char c) {
if (c == '+' || c == '-') return 1;
if (c == '*' || c == '/') return 2;
return 0;
}
static void to_postfix(const char *in, char *out) {
char st[64];
int top = -1, k = 0;
for (; *in; in++) {
char ch = *in;
if (isalnum((unsigned char)ch)) out[k++] = ch;
else if (ch == '(') st[++top] = ch;
else if (ch == ')') {
while (top >= 0 && st[top] != '(') out[k++] = st[top--];
top--;
} else {
while (top >= 0 && prec(st[top]) >= prec(ch)) out[k++] = st[top--];
st[++top] = ch;
}
}
while (top >= 0) out[k++] = st[top--];
out[k] = '\0';
}
int main(void) {
const char *tests[] = {"A+B*C", "(A+B)*C", "A*B+C/D"};
char out[64];
for (int i = 0; i < 3; i++) {
to_postfix(tests[i], out);
printf("%s -> %s\n", tests[i], out);
}
return 0;
}