User Tools

Site Tools


functions

Functions are procedures similar to subroutines, and the same rules largely apply. The main difference between functions and subroutines is that functions return a value. A function is declared and defined with the keyword func.

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

decl func multiply(x:uint, y:uint):uint;

dim a, b:uint = 10;
dim c:uint;

main do

  c = multiply(a, b);
  print(c);

end

func multiply(x:uint, y:uint):uint
do
  multiply = x * y;
end
Output:

100


function result

There are two ways to return a value from a function. One way is to assign a value directly to the function's name, aka identifier, as shown in the example above. Another way is to use the keyword return.

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

decl func multiply(x:uint, y:uint):uint;

dim a, b:uint = 10;
dim c:uint;

main do

  c = multiply(a, b);
  print(c);

end

func multiply(x:uint, y:uint):uint
do
  return x * y;
end
The return statement can be used anywhere inside the function to exit immediately. If the return statement does not include a value, then the most recent value that was assigned to the function's identifier will be returned.

user-defined types

A function can be of a user-defined type (udt), in which case memory is reserved for that type when the function is initialized. This means that there is no need to declare the udt separately as a local instance in order to access it and return it as the function's result, as the udt's fields can be accessed directly from the function's identifier:

' SharpBASIC record function programming example
' ----------------------------------------------
incl "lib/sys.sbi";

record r_buffer is
  a: int;
  b: byte * 16;
end

decl func thisBuffer(s: str): r_buffer;

dim r: r_buffer;

main do
  r = thisBuffer("this is a buffer");
  print(r.b);
  print(r.a);
end

func thisBuffer(s: str): r_buffer
do
  thisBuffer.a = 1;
  thisBuffer.b = s;
end
Output:

this is a buffer

1

functions.txt · Last modified: 2023/07/10 15:17 by admin