Functions

A function is a named block of code that can be called from anywhere in your program. Functions may accept input (parameters) and return a value.

Built-in Functions

RCBasic includes over 200 built-in functions. You have already used several:

' Input$() — returns user input as a string
name$ = Input$("What is your name? ")

' Val() — converts a string to a number
num = Val("42")

' Abs() — returns the absolute value
Print Abs(-7) ' → 7

' Date$() — returns the current date as a string
Print Date$()

' UCase$() — returns a string converted to uppercase
Print UCase$("hello") ' → HELLO

User-Defined Functions

You can define your own functions with Function / End Function:

Function Add(a, b)
Add = a + b ' assign the return value to the function name
End Function

result = Add(3, 5)
Print result ' → 8

String-returning functions must end with $:

Function Greet$(name$)
Greet$ = "Hello, " + name$ + "!"
End Function

Print Greet$("Alice") ' → Hello, Alice!

Subroutines (Sub)

A Sub is like a function but does not return a value:

Sub PrintLine()
Print "--------------------"
End Sub

PrintLine()

Parameters

Parameters are listed in parentheses and separated by commas. RCBasic passes numbers by value and strings by value by default. Use ByRef to pass by reference (the function can modify the caller’s variable):

Sub Swap(ByRef a, ByRef b)
Dim temp
temp = a
a = b
b = temp
End Sub

x = 10 : y = 20
Swap(x, y)
Print x; " "; y ' → 20 10

See also

Scope — Variable visibility inside and outside functions.