Is vala "jump by reference" or "jump by value"?

Or are there pointers and links like C ?

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

+3


source to share


2 answers


First of all, you must understand that the vala compiler is valac

compiled to C (as the source language) by default . The code is then compiled using the C compiler (usually gcc

).

valac -C example.vala

will compile with example.c

So, you can check the resulting C code yourself.

Now to the real question:

Vala supports both call-by-value

and call-by-reference

. It's even slightly finer grained than this one.

Let's take an example using the simple data type C (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 will not affect the caller.

Call by reference with ref

:



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

      

The address will be copied into the function. Anything you do with the value

inside my_func

will also display on the caller side.

Call by reference with out

:

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

      

Basically the same as, ref

but the value doesn't need to be initialized before being my_func

called.

For data types based on GObject

(non-static classes), it gets more complicated as you need to consider memory management.

Since they are always manipulated with pointers (implicitly), modifiers ref

and `out 'now reflect how the (implicit) pointer is passed.

It adds another layer of indirection, so to speak.

string

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

Although discouraged , Vala also supports pointers, so you can have int *

or MyClass *

, as in C.

+4


source


Technically, it is passed by value because the underlying code is converted to C. Simple types (numeric types, booleans, enums, flags) are passed by value. Strings are passed by reference, but since they are immutable, they can also be passed by value.



However, arrays, objects, and structures are passed using pointers in C, so they are traversed by reference. There are also modifiers ref

, and out

to work with the options that make the parameters passed by reference.

+1


source







All Articles