gbdk-2020 | GameBoy Development Kit |
| download: https://git.y1.nz/archives/gbdk.tar.gz | |
| README | Files | Log | Refs | LICENSE |
gbdk-lib/examples/gb/rpn/rpn.c
1 #include <stdint.h>
2 #include <stdio.h>
3 #include <ctype.h>
4
5 #define MAXOP 40
6 #define NUMBER '0'
7 #define STACKSIZE 40
8
9 uint8_t sp;
10 int16_t stack[STACKSIZE];
11
12 char s[MAXOP];
13 uint8_t pos;
14 int16_t n;
15
16 void push(int16_t l)
17 {
18 if(sp < STACKSIZE)
19 stack[sp++] = l;
20 else
21 puts("Stack full");
22 }
23
24 int16_t pop(void)
25 {
26 if(sp > 0)
27 return stack[--sp];
28 else
29 puts("Stack empty");
30 return 0;
31 }
32
33 int16_t top(void)
34 {
35 if(sp > 0)
36 return stack[sp-1];
37 else
38 puts("Stack empty");
39 return 0;
40 }
41
42 int8_t read_op(void)
43 {
44 if(pos == 0) {
45 gets(s);
46 }
47
48 while(s[pos] == ' ' || s[pos] == '\t')
49 pos++;
50
51 if(s[pos] == '\0') {
52 pos = 0;
53 return('\n');
54 }
55
56 if(!isdigit(s[pos]))
57 return(s[pos++]);
58
59 n = s[pos] - '0';
60 while(isdigit(s[++pos]))
61 n = 10 * n + s[pos] - '0';
62
63 return NUMBER;
64 }
65
66 void main(void)
67 {
68 int8_t type;
69 int16_t op2;
70
71 puts("RPN Calculator");
72 sp = 0;
73 pos = 0;
74
75 while((type = read_op()) != 0) {
76 switch(type) {
77 case NUMBER:
78 push(n);
79 break;
80 case '+':
81 push(pop() + pop());
82 break;
83 case '*':
84 push(pop() * pop());
85 break;
86 case '-':
87 op2 = pop();
88 push(pop() - op2);
89 break;
90 case '/':
91 op2 = pop();
92 if(op2 != 0)
93 push(pop() / op2);
94 else
95 puts("Divide by 0");
96 break;
97 case '\n':
98 printf("==> %d\n", top());
99 break;
100 }
101 }
102 }
This webpage is intended to be an accessible preview of this repository. To get a fuller picture, clone it and use the git CLI.