40 likes | 213 Views
Stack Machine + AST + Execution Stack Diagram. First Large Example: A Calculator + AST + ESD.
E N D
Stack Machine + AST + Execution Stack Diagram • First Large Example: A Calculator + AST + ESD Imperative and System Programming, B. Hirsbrunner, diuf.unifr.ch/pai/ip, Lecture 5 – 19 October 2011Stack Machine + AST + ESD: ~45’ + ~30’ + ~15’; Tutorials: UNIT testing: ~45’; Exercises: ~45’
S5 – 19 October 2011 * Hint:use the reverse polish notation, i.e. an infix expression like (1-2)*(3+4) is entered as the postfix expression 1 2 - 3 4 + * - + 1 2 3 4 First Large Example: A Calculator Example: Write a calculator program that provides the operators +, -, *, and /. • Pseudo C code • while (next operator or operand is not end-of-file indicator) • if (number) • push it • elseif (operator) • pop operands • do operation • push result • elseif (newline) • pop and print top of stack • else • error Skeleton Program #include … #define … function declarations for main main() {…} external variables for push and pop void push(double f) {…} double pop(void) {…} int getop(char s[]) {…}
calculator.c #include <stdio.h> #include <stdlib.h> #include "calc.h" #define MAXOP 100 main() {…} calculator.c stack.c getop.c getch.c Dependency graph(all files share calc.h) getch.c stack.c getop.c #include <stdio.h> #include "calc.h" #define MAXVAL 100 int sp = 0; double val[MAXVAL]; void push(double) {…} double pop(void) {…} #include <stdio.h> #include <ctype.h> #include "calc.h" int getop(char []) {…} #include <stdio.h> #include "calc.h" #define BUFSIZE ‘100’ char bufsize[BUFSIZE ]; int bufp = 0; int getch(void) {…} void ungetch(int) {…} Calculator : Header Files (1/2) calc.h void push(double); double pop(void); #define NUMBER ‘0’ int getop(char []); int getch(void); void ungetch(int); calc.h calc.h calc.h
calculator.c my_stack.h calculator.c #include <stdio.h> #include <stdlib.h> #include "my_stack.h" #include "my_special_io.h" #define MAXOP 100 main() {…} void push(double); double pop(void); my_stack.h my_special_io.h my_special_io.h my_stack.c my_special_io.c #define NUMBER ‘0’ int getop(char []); my_io.h my_io.h my_io.c int getch(void); void ungetch(int); Dependency graph my_io.c my_stack.c my_special_io.c #include <stdio.h> #include "my_stack.h" #define MAXVAL 100 int sp = 0; double val[MAXVAL]; void push(double) {…} double pop(void) {…} #include <stdio.h> #include <ctype.h> #include "my_io.h" #include "my_special_io.h" int getop(char []) {…} #include <stdio.h> #include "my_io.h" #define BUFSIZE ‘100’ char bufsize[BUFSIZE ]; int bufp = 0; int getch(void) {…} void ungetch(int) {…} Calculator : Header Files (2/2)