Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Procedures

A procedure gives a piece of work a name. tiko has two kinds: a sub does something and returns nothing, and a function computes a value and hands it back.

'' A sub does something. A function answers something.

sub Greet( byref who as ustring )
    print "Hello, " & who & "!"
end sub

function Square( byval n as int32 ) as int32
    return n * n
end function

'' function = sets the result and carries on; return leaves at once.
function Sign( byval n as int32 ) as ustring
    function = "positive"
    if n < 0 then return "negative"
    if n = 0 then function = "zero"
end function

Greet( "world" )
print "Square( 12 ) ="; Square( 12 )
print Sign( -4 ) & " " & Sign( 0 ) & " " & Sign( 9 )

'' A function's answer may be ignored; the call still happens.
function Report( ) as int32
    print "Report ran"
    return 1
end function

Report( )

Output

Hello, world!
Square( 12 ) = 144
negative zero positive
Report ran

Parameters go in parentheses after the name, each with its type and a word saying how it is passed (see Parameters). A function names its result type after the parameter list, as in as int32.

A function has two ways to set its result:

  • return value sets the result and leaves the function at once.
  • function = value sets the result and carries on. Sign uses it to set a default answer first and change it further down.

A function that reaches end function without setting a result returns zero (or an empty string), with no warning, so make sure every path sets one.

A function can also be called as a statement, as Report( ) is: the call runs and the result is thrown away.

Procedures are written at the top level of a file, and statements at the top level run in order around them. A procedure sees only its parameters and its own variables, not the variables of the code that calls it.

Activities

  1. Write a function Cube and print the cubes of 1 to 5.
  2. Remove the if n = 0 line from Sign and predict what Sign( 0 ) returns.