Skip to content

Subroutines

Saurabh Joshi edited this page Jul 27, 2016 · 2 revisions

Subroutines

A subroutine is a sequence of instructions that is modular and can be executed multiple times. If you are familiar with any programming language, you may see that subroutines are similar to functions. If you only dealt with functions in mathematics, you could view subroutines in terms of inputs and outputs. However the way they perform operations can be quite different. Furthermore, MARIE doesn't provide a way to specify input or output values (for programmers, parameter or return values).

MARIE provides a way to call these subroutines by using the JnS instruction, and normal program execution can be resumed once the subroutine exits by using the JumpI instruction.

Example

Here is an example that prints the variable X, then halts the program:

/ Enter subroutine PrintVariableX
JnS PrintVariableX
Halt

PrintVariableX, HEX 000 / Used for storing return address
                Load X
                Output

                / Exit subroutine PrintVariableX
                JumpI PrintVariableX

X, DEC 42

The JnS instruction stores the address of the next instruction after it was called. In this case, the memory address points to the Halt instruction. This is the return address which will be later used to restore program execution. Once it has done that, it then jumps to the instruction immediately below the label PrintVariableX, by using the memory address of PrintVariableX and incrementing that value once.

Once the subroutine performs its intended task, and runs the JumpI instruction, it loads the memory address stored at the PrintVariableX label, and stores it into the PC register. Note that we don't need to increment the PC register here as it is already taken care of in the fetch part of the fetch-decode-execute cycle before it entered the subroutine. Program execution is resumed from where it was, and the program halts as the Halt instruction is executed.

The major part of subroutines is that it can be reused. Here is a slightly modified example that illustrates this.

/ Call subroutine PrintVariableX
JnS PrintVariableX
Load X
Add Y
Store X
JnS PrintVariableX / Call subroutine PrintVariableX again
Halt

PrintVariableX, HEX 000 / Used for storing return address
                Load X
                Output

                / Exit subroutine PrintVariableX
                JumpI PrintVariableX

X, DEC 42
Y, DEC 5

It doesn't matter where you call the subroutines (unless the subroutine calls itself), or how many calls you make to the subroutines. The return address will be overwritten, and program execution will always be resumed to where it was once the subroutine exits.