Differences
This shows you the differences between two versions of the page.
| Previous revision | |||
| — | functions [2026/09/14 19:47] (current) – [Returning a value] jjflash | ||
|---|---|---|---|
| Line 1: | Line 1: | ||
| + | ====== Functions ====== | ||
| + | Functions in XC=BASIC are essentially the same as [[subroutines|Subroutines]], | ||
| + | |||
| + | ===== Defining the return type ===== | ||
| + | |||
| + | A function must always return a type, that is, the type of the value that it returns. You must define the return type in the function definition line using the '' | ||
| + | |||
| + | <code xcbasic> | ||
| + | FUNCTION < | ||
| + | < | ||
| + | END FUNCTION | ||
| + | </ | ||
| + | ===== Calling a function ===== | ||
| + | |||
| + | Functions can not be called using the '' | ||
| + | |||
| + | <code xcbasic> | ||
| + | FUNCTION test AS LONG () | ||
| + | ' -- function body here | ||
| + | END FUNCTION | ||
| + | |||
| + | x = test() | ||
| + | ' -- The variable x will be implicitly defined as LONG | ||
| + | ' -- because the right hand side is a LONG type | ||
| + | </ | ||
| + | |||
| + | <adm note> | ||
| + | For the above reason, there are no void functions in XC=BASIC. [[subroutines|Subroutines]] serve as void functions. | ||
| + | </ | ||
| + | ===== Returning a value ===== | ||
| + | |||
| + | There are two ways to return a value from a function: | ||
| + | |||
| + | * The QBASIC style, by assigning a value to the function name. | ||
| + | * Using the '' | ||
| + | |||
| + | Both styles are accepted in XC=BASIC. Here are two examples to demonstrate each: | ||
| + | |||
| + | <code xcbasic> | ||
| + | ' -- returning value the QBASIC style | ||
| + | FUNCTION test AS BYTE () | ||
| + | test = 42 | ||
| + | END FUNCTION | ||
| + | PRINT test() ' will output 42 | ||
| + | </ | ||
| + | |||
| + | <code xcbasic> | ||
| + | ' -- returning value using the RETURN keyword | ||
| + | FUNCTION test AS BYTE () | ||
| + | RETURN 42 | ||
| + | END FUNCTION | ||
| + | PRINT test() ' will output 42 | ||
| + | </ | ||
| + | |||
| + | The above two codes are identical, but the '' | ||
| + | |||
| + | (TODO: provide example) | ||
| + | |||
| + | Note the use of the '' | ||
| + | |||
| + | <adm warning> | ||
| + | If the code exits from a function before any return value was specified, an undefined value will be returned. | ||
| + | </ | ||