Functions#

A function is a chunk of code, that can be called from elsewhere. You have at least one, the main function, which is executed on the startup of your application.

They help organizing and modularizing your code.

How to use#

For example you can define one with the name “do_something”:

void do_something () {
    stdout.printf ("This is a function.\n");
}

In this case the function contains code, that prints out “This is a function.” on the command line.

Then you can call the function, to execute the code in it:

do_something ();

A full program would look like this:

void do_something () {
    stdout.printf ("Hello, Vala!\n");
}

int main (string[] args) {
    do_something ();
    return 0;
}

Function parameters#

Sometimes a function should behave slightly different, depending on the place from where it is called. This can be implemented with parameters.

You can give a function information, what to do on calling it:

do_something ("do it!");

Then you also need to let the function collect and use this information:

void do_something (string text) {
    stdout.printf ("My argument: %s\n", text);
}

In this case the parameter is of type string and the name text. You can access them from inside of the function like a variable.

A function can also have multiple parameters after each other:

void do_something (string name, int year) {
    stdout.printf ("Name: %s, Year: %i\n", name, year);
}

int main (string[] args) {
    do_something ("Vala", 2006);
}

Return Values#

A function can do an operation, and often should give the result of it back to the caller. This is possible with return values.

First you have to specify the type of the returned value of the function. All your functions already have return types, the void type:

void do_domething () {
    // ...
}

But if you want to return something, it needs to be an actual type. You also need to return a value then:

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

The caller can then store the return value in a variable:

int result = add (1, 3);

The main function#

The main function is a special function, that marks the entry of the program.

It returns int, and takes an array of string arguments:

int main (string[] args) {
    // ...
    return 0;
}

A program usually returns 0 on success, and any other number on failure.

The arguments are the commandline parameters of your program. If you execute your application with

./app --do hello

string args[] will have ["app", "--do", "hello"] in it.

Also useful#

  • If you don’t have a return value, but want to let the function return at a point, you can just use return; without a value.

  • Sometimes the commandline arguments of the main-function are not used. In this case, you can just omit them. You also can change the return type to void, if it is not needed. For example void main () { //....

  • Sometimes you want to use variable length parameters. TODO