|
Constants |
Top Previous Next |
Constants are used to represent values which do not change throughout the program; these values may be strings or numbers. They may either be stated explicitly, or be derived as the result of an expression.
Some examples:
const universal_answer = 42 const copyright = "(c) 2005 Widget Systems Inc." ' this is a string constant const escape_char = `@` ' this constant will contain a numerical value -- the ASCII code for the char @.
const hexi = &hFB ' would create a constant with a value of 251 (&hFB in hex) const bini = &b00110101 ' would create a constant with a value of 53 (&b00110101 in binary)
const width = 10 const height = 15 const area = width * height ' constants may contain expressions which include other constants
dim x as byte const foo = x + 10 ' this will produce a compiler error. Constant expressions may contain only constants.
|
Constants can be useful when you have some values which are used throughout the code; with constants, you can define them just once and then refer to them by their meaningful name. This has the added benefit of allowing you to easily change the value for the constant any time during the development process -- you will just have to change the definition of the constant, which is a single line of code.
|
When defining a list of related constants, it is often convenient to use the Enum Statement and create one data type which contains this list of constants. See also User-Defined Types above. |
When defining a constant within a scope, this constant is visible only from within this scope. It is a good idea to define all constants within header files, and include these files into each compilation unit.
String constants
String constants can include escape sequences to define unprintable characters. This functionality is borrowed from C. Adding unprintable characters to the string has always been rather inconvenient in BASIC language. The only way to do so was like this:
s = "abc"+chr(10)+chr(13) 'add LF/CR in the end
|
In Tibbo Basic you can achieve the same by using escape sequences -- C style:
s = "abc\n\f" ''\n' means LF, '\f' -- CR const STR1 = "abc\x10\x13" 'same result can be achieved using HEX codes of the characters
|
The following standard escape sequences are recognized:
| • | "\0" for ASCII code 0 |
| • | "\a" for ASCII code 7 (&h7) |
| • | "\b" for ASCII code 8 (&h8, BS character) |
| • | "\t" for ASCII code 9 (&h9) |
| • | "\n" for ASCII code 10 (&hA, LF character) |
| • | "\v" for ASCII code 11 (&hB) |
| • | "\f" for ASCII code 12 (&hC) |
| • | "\r" for ASCII code 13 (&hD, CR character) |
| • | "\e" for ASCII code 27 (&h1B, ESC character) |
Any ASCII character, printable or unprintable, can be defined using its HEX code. The following format should be used: "\x00" where "00" is the HEX code of the character. Notice, that two digits should be present on the code, for example: "\x0A" -- leading zero must not be omitted.
\