Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is vala a "pass by reference" or "pass by value"?

Or there exists pointers and references like C?

I'm trying to get started with vala but is good to know if vala is "pass by reference" or "pass by value"

like image 514
Jean Pierre Dudey Avatar asked Mar 16 '23 13:03

Jean Pierre Dudey


1 Answers

First of all you should understand that the default vala compiler valac compiles to C (as an itermediate language). The code is then compiled using a C compiler (usually gcc).

valac -C example.vala will compile to example.c

So you can inspect the produced C code yourself.

Now to the real question:

Vala supports both call-by-value and call-by-reference. It is even a bit more fine grained than that.

Let's take an example using a plain C data type (int).

Call-by-value:

public void my_func (int value) {
    // ...
}

The value will be copied into the function, no matter what you do with value inside my_func it won't affect the caller.

Call-by-reference using ref:

public void my_func (ref int value) {
    // ...
}

The address will be copied into the function. Everything you do with value inside my_func will be reflected on the caller side as well.

Call-by-reference using out:

public void my_func (out int value) {
    // ...
}

Basically the same as ref, but the value doesn't have to be initialized before calling my_func.

For GObject based data types (non-static classes) it gets more complicated, because you have to take memory management into account.

Since those are always managed using pointers (implictly) the ref and `out´ modifiers now reflect how the (implicit) pointer is passed.

It adds one more level of indirection so to speak.

string and array data types are also internally managed using pointers and automatic reference counting (ARC).

Though discouraged, Vala also does support pointers, so you can have an int * or MyClass * just like in C.

like image 174
Jens Mühlenhoff Avatar answered Mar 18 '23 02:03

Jens Mühlenhoff