Step 1 of 5 · Reading · ~1 min
Learn
Subs, Functions, and Types
FreeBASIC distinguishes:
- Sub — does work, no return value
- Function — returns a value
Sub Greet(name AS STRING)
PRINT "Hello, " + name
End Sub
Function Square(n AS INTEGER) AS INTEGER
Return n * n
End Function
Greet("Ada")
PRINT Square(5)
Functions return via Return (modern) or by assigning to the function name (classic):
Function Cube(n AS INTEGER) AS INTEGER
Cube = n * n * n ' classic style
End Function
Pass-by-reference with BYREF:
Sub Swap(BYREF a AS INTEGER, BYREF b AS INTEGER)
DIM tmp AS INTEGER
tmp = a
a = b
b = tmp
End Sub
Default is BYVAL (by value) - a Sub that assigns to a plain n AS INTEGER
parameter changes only its own copy. BYREF is what makes a parameter an
output parameter.
Default arguments:
Function Greet(name AS STRING, greeting AS STRING = "Hello") AS STRING
Return greeting + ", " + name
End Function
PRINT Greet("Ada") ' Hello, Ada
PRINT Greet("Ada", "Hi") ' Hi, Ada
Recursion works fine — no special keyword needed.
Printing a number without the space in front of it
PRINT reserves one column for a number's sign, so a positive number comes out
with a leading space. The grader compares that space, and it is the difference
between passing and failing this lesson's exercise:
PRINT 1024 ' writes " 1024" - note the space
PRINT LTRIM(STR(1024)) ' writes "1024"
PRINT "n=" & 1024 ' writes "n=1024" - & converts without padding
STR converts a number to a string, LTRIM strips the leading blank, and &
concatenates a number onto a string without adding anything.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…