2.19. Functions

A function is declared in Qore by using the key word sub (for subroutine) as follows:

[return_type] subfunction_name([[type] variable1, ...]) {
    statements;
}
or the alternate syntax with the returns keyword:
subfunction_name([[type] variable1, ...]) [returnstype] {
    statements;
}

Variables listed in parentheses after the function name are the parameters to the function and automatically get local lexical scoping. In order to process a variable number of arguments to a function, the $argv variable (local variable) is instantiated as a list with the remaining arguments passed to the function. Type declarations optionally precede the parameter variable and will restrict any arguments passed to the type declared. The same function can be declared multiple times if each declaration has different parameter types; this is called overloading the function.

Functions use the return statement to provide a return value. Function names must be valid Qore identifiers.

The return type of the function can be given by placing a type declaration before the sub keyword (the older syntax with the returns keyword after the parameter list is still accepted as well).

Note that parameter and return types are required when the PO_REQUIRE_TYPES or PO_REQUIRE_PROTOTYPES parse options are set.

Note

Variables passed as function arguments are passed by value by default, unless the caller places a "\" character before an lvalue in the argument list. In this case the function must have a parameter defined to accept the variable passed by reference. Any changes to the local variable will be reflected in the original variable for variables passed by reference. Also note that it is illegal to pass an argument by reference in a background expression.

Functions can return values to the calling expression by using the return statement, with the following syntax:

returnexpression;

Here is an example function declaration returning a value:

#!/usr/bin/qore
#
# function declaration example

int sub print_string(string $string) {
    print("%s\n", $string);
    return 1;
}

Functions may also be recursive. Here is an example of a recursive Qore function implementing the Fibonacci function:

#!/usr/bin/qore
#
# recursive function example

int sub fibonacci(int $num) {
    if ($num == 1)
        return 1;
    return $num * fibonacci($num - 1);
}

Note

Function names are resolved during the second parse pass; therefore functions do not need to be declared before being referenced. This allows an easy definition of 2 or more self-referencing functions.

There are no comments yet

Leave a Comment



?
? ?
?

 
Powered by TalkBack