STATIC - mkilgore/QB64pe GitHub Wiki
The STATIC keyword is used in declaration statements to control where variables are stored.
- A STATIC list can be used in SUB and FUNCTION procedures to designate one or more variables to retain their values.
- Variables and arrays with static storage will retain their values in between procedure calls. The values may also be used recursively.
- STATIC can be used after the name of a SUB or FUNCTION in the procedure to force all variables to retain their values.
- Recursive procedures may be required to be STATIC to avoid a Stack Overflow! QB64 programs may just close!
- $STATIC defined program arrays cannot be re-sized or use _PRESERVE.
END FUNCTION Bin$ (n&) STATIC 'comment out STATIC to see what happens! DIM p%, s$ IF...THEN 2 ^ p% > n& THEN p% = 0 ELSE IF...THEN n& AND (boolean) 2 ^ p% THEN s$ = "1" + s$ ELSE s$ = "0" + s$ IF...THEN n& > 2 ^ p% THEN p% = p% + 1 s$ = Bin$(n&) 'recursive call to itself ELSE: p% = 0 END IF END IF IF...THEN s$ = "" THEN Bin$ = "0" ELSE Bin$ = s$ END FUNCTION '' '' |
- Explanation: The FUNCTION above returns a STRING value representing the bits ON in an INTEGER value. The string can be printed to the screen to see what is happening in a port register. STATIC keeps the function from overloading the memory "Stack" and is normally REQUIRED when recursive calls are used in QBasic! QB64 procedures will close without warning or error!
PRINT Factorial(0) PRINT Factorial(5) PRINT Factorial(50 FUNCTION Factorial# ( n AS DOUBLE ) CONST maxNToCache = 50 STATIC resultCache() AS DOUBLE STATIC firstCall AS INTEGER ' The lookup table is initially empty, so re-size it.. IF...THEN firstCall = 0 IF...THEN firstCall = -1 REDIM resultCache(maxNToCache) AS DOUBLE ' ..and pre-calculate some factorials. resultCache(0) = 1 resultCache(1) = 1 resultCache(2) = 2 IF...THEN ' See if we have the result cached. If so, we're done. IF...THEN n <= maxNToCache IF...THEN IF...THEN resultCache(n) <> 0 IF...THEN Factorial = resultCache(n) EXIT FUNCTION IF...THEN IF...THEN ' If not, we use recursion to calculate the result, then cache it for later use: resultCache(n) = INT(n) * Factorial(INT(n) - 1) Factorial = resultCache(n) END FUNCTION |
1 120 3.041409320171338D+64 |
Navigation:
Go to Keyword Reference - Alphabetical
Go to Keyword Reference - By usage
Go to Main WIKI Page