vala Functions Basic functions


Example

A function is defined by at least its return type and an unique name.

void say_hello () {
    print ("Hello, world!\n");   
}

Then, to call it just use the name of the function followed by a parenthese.

say_hello ();

Functions can also have parameters between the parentheses, defined by their types and names and separated by commas. Then you can just use them as normal variables into your function.

int greet (string name, string family_name) {
    print ("Hello, %s %s!\n", name, family_name);
}

To call a function with parameters, just put a variable or a value between the parentheses.

string name = "John";
greet (name, "Doe");

You can also return a value which can be assigned to a variable with the return keyword.

int add (int a, int b) {
    return a + b;
}

int sum = add (24, 18);

All code path should end with a return statement. For instance, the following code is invalid.

int positive_sub (int a, int b) {
    if (a >= b) {
        return a - b;
    } else {
        // Nothing is returned in this case.
        print ("%d\n", b - a);
    }
}