Last time, we implemented our “Postfix and the Stack” program in JavaScript. Here's a version in c, that will lead to some more interesting results.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STACK 100
#define MAX_TOKENS 100
double stack[MAX_STACK];
int stack_top = -1;
void push(double value) {
if (stack_top < MAX_STACK - 1) {
stack[++stack_top] = value;
} else {
fprintf(stderr, "Stack overflow\n");
exit(1);
}
}
double pop() {
if (stack_top >= 0) {
return stack[stack_top--];
} else {
fprintf(stderr, "Stack underflow\n");
exit(1);
}
}
void add() {
double a = pop();
double b = pop();
push(a + b);
}
void sub() {
double a = pop();
double b = pop();
push(a - b);
}
void mul() {
double a = pop();
double b = pop();
push(a * b);
}
void dvd() {
double a = pop();
double b = pop();
if (b != 0) {
push(a / b);
} else {
fprintf(stderr, "Division by zero\n");
exit(1);
}
}
int main() {
char source[] = "add div 1 2 mul 3 4";
char* tokens[MAX_TOKENS];
int token_count = 0;
// Tokenize the string
char* token = strtok(source, " ");
while (token != NULL && token_count < MAX_TOKENS) {
tokens[token_count++] = token;
token = strtok(NULL, " ");
}
// Process tokens in reverse order
for (int i = token_count - 1; i >= 0; i--) {
if (strcmp(tokens[i], "add") == 0) add();
else if (strcmp(tokens[i], "sub") == 0) sub();
else if (strcmp(tokens[i], "mul") == 0) mul();
else if (strcmp(tokens[i], "div") == 0) dvd();
else push(atof(tokens[i]));
}
if (stack_top >= 0) {
printf("Result: %f\n", stack[0]);
} else {
printf("No result\n");
}
return 0;
}
This works, but there are a couple things wrong with it:
the if-ladder: a switch would be better
string operations: branching on integers would be better
In the next article, we'll do the string operations up front, generating an intermediate form that will run faster. After that we'll use the intermediate form to generate assembly directly.