Velo by Example: Pointers

Velo has type-safe, memory-safe pointers for pass-by-reference semantics. No pointer arithmetic is allowed.

Create a pointer with an initial value, a null pointer, or take the address of a variable with &.

ptr[int] p = new ptr[int](42);
ptr[int] nullPtr = new ptr[int];
ptr[int] alsoNull = null;

int x = 10;
ptr[int] px = &x;

Dereference with .val, .*, or the prefix * operator.

ptr[int] p = new ptr[int](42);

int value = p.val;    # 42
int value2 = *p;      # 42

p.val = 100;
*p = 200;

The address-of operator creates a reference to an existing variable. Modifying through the pointer changes the original.

int x = 10;
ptr[int] px = &x;
px.val = 20;
# x is now 20

A classic swap function using pointers.

func swap(ptr[int] a, ptr[int] b) void {
    int tmp = a.val;
    a.val = b.val;
    b.val = tmp;
};

int x = 10;
int y = 20;
swap(&x, &y);
# x = 20, y = 10

Check for null before dereferencing.

ptr[int] p = new ptr[int];

if (p != null) {
    int v = p.val;
} else {
    term.println("Pointer is null");
};