Created
February 15, 2021 08:54
-
-
Save kofuk/30c6b8d844a7b6e961e89977248a9097 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#define OP_ADD -1 // '+' | |
#define OP_SUB -2 // '-' | |
#define OP_MUL -3 // '*' | |
#define OP_DIV -4 // '/' | |
char op[] = {'+', '-', '*', '/'}; | |
int stack[1024]; | |
int sp; | |
void push(int); | |
int pop(void); | |
void do_add(void) { | |
int n1 = pop(); | |
int n2 = pop(); | |
push(n2 + n1); | |
} | |
void do_sub(void) { | |
int n1 = pop(); | |
int n2 = pop(); | |
push(n2 - n1); | |
} | |
void do_mul(void) { | |
int n1 = pop(); | |
int n2 = pop(); | |
push(n2 * n1); | |
} | |
void do_div(void) { | |
int n1 = pop(); | |
int n2 = pop(); | |
push(n2 / n1); | |
} | |
void (*op_func[])(void) = { | |
&do_add, | |
&do_sub, | |
&do_mul, | |
&do_div, | |
}; | |
void print_stack(int num) { | |
stack[sp] = num; | |
puts(""); | |
puts("| |"); | |
puts("+------+"); | |
for (int i = sp; i >= 0; --i) { | |
int num = stack[i]; | |
if (-4 <= num && num < 0) { | |
num *= -1; | |
printf("| %4c |\n", op[num - 1]); | |
} else { | |
printf("| %4d |\n", num); | |
} | |
puts("+------+"); | |
} | |
} | |
void push(int num) { | |
print_stack(num); | |
if (-4 <= num && num < 0) { | |
num *= -1; | |
op_func[num - 1](); | |
} else { | |
stack[sp++] = num; | |
} | |
} | |
int pop(void) { | |
return stack[--sp]; | |
} | |
int main(void) { | |
push(12); | |
push(19); | |
push(OP_ADD); // '+' | |
push(2); | |
push(OP_MUL); // '*' | |
push(2); | |
push(OP_SUB); // '-' | |
printf("%d\n", pop()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment