-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
66 lines (57 loc) · 1.07 KB
/
main.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
#include <stdbool.h>
#include <stdio.h> // printf
typedef enum {
PSH,
ADD,
POP,
SET,
HLT
} InstructionSet;
typedef enum {
A, B, C, D, E, F,
IP, SP,
NUM_REGISTERS
} Registers;
#define ip (registers[IP]) // Instruction pointer
#define sp (registers[SP]) // Stack pointer
const int program[] = {
PSH, 5,
PSH, 6,
ADD,
POP,
HLT
};
// int ip = 0; // instruction pointer
// int sp = -1;
int stack[256];
int registers[NUM_REGISTERS];
bool running = true;
int fetch() {
return program[ip];
}
void eval(int instr) {
int x, y;
switch (instr) {
case ADD:
y = stack[sp--];
x = stack[sp--];
stack[++sp] = x + y;
break;
case PSH:
stack[++sp] = program[++ip];
break;
case POP:
x = stack[sp--];
printf("POP: %d\n", x);
break;
case HLT:
running = false;
break;
}
}
int main() {
while (running) {
eval(fetch());
ip++; // increment instruction pointer
}
}