Exercise 49: A Tiny Virtual Machine – Part 2: Interpreter Core

Goals:

  • Implement the instruction execution loop.
  • Handle registers and program counter.

Topics Covered:

  • switch-case based dispatch loop.
  • Registers R0 to R3, memory-mapped.
  • Executing instructions from memory.

Code Concepts:

cCopyEditvoid run(VM *vm) {
    while(vm->running) {
        unsigned char instr = vm->code[vm->ip++];
        switch(instr) {
            case OP_LOAD: // LOAD Rx, imm
                vm->registers[vm->code[vm->ip++]] = vm->code[vm->ip++];
                break;
            case OP_HLT:
                vm->running = 0;
                break;
            // ...
        }
    }
}