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

Static locals

An ordinary local variable is created fresh on every call. A static local is created once and keeps its value from one call to the next, which gives a procedure a memory without a variable outside it:

'' A static local is created once and keeps its value between calls.
function NextTicket( ) as int32
    static as int32 counter = 100      '' set once, before the first call
    counter += 1
    return counter
end function

print NextTicket( ); NextTicket( ); NextTicket( )

'' An ordinary local starts again on every call.
function Fresh( ) as int32
    dim as int32 counter = 100
    counter += 1
    return counter
end function

print Fresh( ); Fresh( ); Fresh( )

'' A static array works too: this one remembers the last three values.
sub Remember( byval value as int32 )
    static as int32 recent( 0 to 2 )
    static as int32 slot = 0
    recent( slot ) = value
    slot = ( slot + 1 ) mod 3
    print "recent:"; recent( 0 ); recent( 1 ); recent( 2 )
end sub

Remember( 7 )
Remember( 8 )
Remember( 9 )
Remember( 10 )

Output

 101 102 103
 101 101 101
recent: 7 0 0
recent: 7 8 0
recent: 7 8 9
recent: 10 8 9

counter in NextTicket is set to 100 once, before the first call, and each call moves it on. Fresh declares the same variable with dim, so every call starts again from 100.

An array can be static too. Remember keeps a ring of the last three values and a slot that wraps round, so the fourth value overwrites the first.

A static belongs to the procedure, not to a call, so every call shares it: the calls of a recursion, and calls from two threads at once. Reset it yourself when its job is done, and give a procedure that several threads call no static it writes to; Concurrency has the tools for shared state.

Activities

  1. Make NextTicket start at 1 and print five tickets.
  2. Change Remember to keep the last five values.