GOOC - Game Oriented Object C

GOOC - Game Oriented Object C

Next: Subroutine Parameters, Up: Subroutines
[Contents]

9.1. Defining a Subroutine

9.1. Defining a Subroutine

You write a subroutine definition to specify what a subroutine actually does. A subroutine definition consists of information regarding the subroutine’s name, names of parameters, extra subroutine modifiers, and the body of the subroutine. The subroutine body is a series of statements enclosed in braces, similar to a block.

Here is the general form of a subroutine definition: sub subroutine-name pre-modifiers (parameter-list) modifiers { subroutine-body } subroutine-name is the name of the subroutine. The name must be unique to the subroutine, otherwise a compiler error will be thrown. parameter-list is the list of parameters' names that can be used by the defined subroutine, separated by commas. modifiers and pre-modifiers are sets of subroutine modifiers (which also includes none at all), described in a later section. subroutine-body is the statements content of the subroutine.

Here is an example of a simple subroutine, which simply increases the x field by a set amount: sub AddX (amount) { x += amount }

Unlike in C, subroutines cannot return values. If you wish to store the result of a subroutine, you will have to make the subroutine write said result into some field, at least temporarily, so it can be later retrieved if needed: sub GetSquare(number) { misc = number * number } Here, the result of the power of 2 of number will be stored in the misc field. Code that calls this subroutine can then read the misc field after calling it in order to get the result: ... GetSquare(3) var the_square = misc ...