-
Notifications
You must be signed in to change notification settings - Fork 139
/
mac.c
76 lines (63 loc) · 1.27 KB
/
mac.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/**
This is almost identical to the articles
VM
**/
#include <stdio.h>
#include <stdbool.h>
bool running = true;
int ip = 0;
int sp = -1;
int stack[256];
typedef enum {
PSH,
ADD,
POP,
HLT
} InstructionSet;
const int program[] = {
PSH, 5,
PSH, 6,
ADD,
POP,
HLT
};
int fetch() {
return program[ip];
}
void eval(int instr) {
switch (instr) {
case HLT: {
running = false;
printf("done\n");
break;
}
case PSH: {
sp++;
stack[sp] = program[++ip];
break;
}
case POP: {
int val_popped = stack[sp--];
printf("popped %d\n", val_popped);
break;
}
case ADD: {
// first we pop the stack and store it as a
int a = stack[sp--];
// then we pop the top of the stack and store it as b
int b = stack[sp--];
// we then add the result and push it to the stack
int result = b + a;
sp++; // increment stack pointer **before**
stack[sp] = result; // set the value to the top of the stack
// all done!
break;
}
}
}
int main() {
while (running) {
eval(fetch());
ip++; // increment the ip every iteration
}
}