User Tools

Site Tools


subroutines

SharpBASIC offers full support for subroutines, also referred to as procedures or subprograms. Just like functions, subroutines allow for pieces of isolated code with their own scope, i.e. a variable declared in a subroutine, aka a local variable, can have the same name as a global variable, in which case the local variable takes precedence:

' SharpBASIC subroutine programming example 1
' -------------------------------------------
incl "lib/sys.sbi";

decl sub printNumber();

dim a: uint;

main do

  a = 10;
  print(a);

  printNumber();

end

sub printNumber()
  dim a: uint;
do
  a = 5;
  print(a);
end
Output:

10

5


Subroutines must be declared in the prologue section of a program. This is the section before the statement main do .. end. See also program structure. Subroutines are declared with the declare statement decl, followed by the keyword sub and the subroutine's header. A declare statement ends with a statement terminator. The subroutine's header in a declare statement must match the actual subroutine's header exactly!

Subroutines are defined in the epilogue section. This is the section that follows on the main do .. end statement.

A subroutine begins with the sub statement, followed by the subroutine's header. The header is not followed by a statement terminator because the sub-statement is an execution compound statement, i.e. it is followed by a do .. end block, similar to the [main|main]] statement, whereby the keyword end is a compound statement terminator. See also statements.

A subroutine has its own prologue section where local variables can be declared. This section comes before the keyword do.

Subroutines can optionally pass parameters by declaring a list of variables in the subroutine's header, separated by comma's:

' SharpBASIC subroutine programming example 2
' -------------------------------------------
incl "lib/sys.sbi";

decl sub printMultiply(x:uint, y:uint);

dim a, b:uint = 10;

main do

  printMultiply(a, b);

end

sub printMultiply(x:uint, y:uint)
do
  print(x * y);
end
Output:

100


Subroutines can also be defined in modules without a main do .. end section. This is useful for larger projects and for building libraries.

The return statement can be used anywhere inside the subroutine to exit immediately.

subroutines.txt · Last modified: 2023/07/05 14:27 by admin