suve

awful: tutorial: constants

Sometimes in our code appear some values - be it numbers, strings, or whatever else - which have a special meaning and repeat in many places. Everything is fine in using literals everywhere… until we need to change this special value and have to look for every place it appears, which can be very tedious. We can prevent this by using constants.

!const =LIMIT i50

:set &fib :arr i1 i1
:set &c i2
!repeat
    :set &fib[$c] :add $fib[:sub $c i1] $fib[:sub $c i2]
    :add &c i1
!until :gt $c =LIMIT

:write s'Enter number (0 - ' =LIMIT s'): '
:read &c

!if :or (:lt $c i0 | :gt $c =LIMIT)
    :writeln s'Number outside range!'
!else
    :writeln s'fibon(' $c s') == ' $fib[$c]
!fi

The example above demonstrates the use of constants. They are declared using the !const construct, after which follows the const name - which must start with the equals character (=) - and then, the value of the const, which must be a value literal (or, eventually, another const). It is currently impossible to use the result of a function call as the value of a const. To use a const, just place it anywhere in the code, like you would place a variable. The value of a const cannot be modified anyhow - they are always passed by value.

In the example above, we declared the const =LIMIT with int value 50 and then used it to make sure that number of loop operations, range printing and range checking are all compliant.


Next: ⇒ Functions ⇒
Back: ⇐ Loops ⇐

wikipage modified on 2014/0601/2317