PBASIC Programming/Subroutines

Reusing Code

edit

We have seen in our chapters on loops that there are many times that we want to repeat certain blocks of code multiple times. A loop repeats these blocks one after the other, but what if we want to repeat a block of code at different times?

We can use a special tool called a subroutine to make a block of code repeatable. We can "call" our subroutine at any point in our program, and when the subroutine ends, the control flow will jump back to where it was.

When we move control flow into a subroutine, we say that we "call" the subroutine, or that we "enter" it. Similarly, when the subroutine has completed, we say that we "exit" the subroutine, or that we "return from it".

GOSUB and RETURN

edit

Subroutines start with a label. Instead of using a GOTO jump, we use the GOSUB instruction to enter the subroutine. The GOSUB does two things:

  1. it jumps to the subroutine's label, like a regular GOTO
  2. it stores the old value of the instruction pointer, so that after the subroutine the control flow can return to where it was.

The second point is important, because it allows us to return to our previous position.

The RETURN instruction, at the end of the subroutine, loads the saved value of the instruction pointer.

Subroutines

edit

A basic subroutine looks like this:

MySubroutine:
   ... 'Do this in the subroutine
RETURN

Readability

edit

One of the big benefits to using subroutines is that they help to make your code much easier to read for other people. Many times the person who writes a program will understand it very well, but it may not be so obvious to other people, such as teammates. For instance, if we have a robot using the BasicStamp, and we want to make that robot walk around in the shape of a square, we can use subroutines to do it easily:

GOSUB MoveForward
GOSUB TurnRight
GOSUB MoveForward
GOSUB TurnRight
GOSUB MoveForward
GOSUB TurnRight
GOSUB MoveForward
GOSUB TurnRight

Or, we can combine our subroutines with a loop to make it even easier:

FOR MyCounter = 1 TO 4
   GOSUB MoveForward
   GOSUB TurnRight
NEXT

The subroutines for MoveForward or TurnRight may be very complicated, but any person can read the small block of code above and understand what the robot will do.