Pointers in Chapel

Chapel supports references, allowing you to pass references to values and variables within your program.

We’ll show how references work in contrast to values with two functions: zeroval and zeroptr. zeroval has an int parameter, so arguments will be passed to it by value. zeroval will get a copy of ival distinct from the one in the calling function.

proc zeroval(ival: int) {
    ival = 0;
}

zeroptr in contrast has a ref int parameter, meaning that it takes a reference to an int. The iptr in the function body can be used directly to modify the value at the referenced address. Assigning a value to a reference changes the value of the original variable.

proc zeroptr(ref iptr: int) {
    iptr = 0;
}

Here’s how we use these functions:

proc main() {
    var i: int = 1;
    writeln("initial:", i);

    zeroval(i);
    writeln("zeroval:", i);

    zeroptr(i);
    writeln("zeroptr:", i);

    // Chapel doesn't have a direct way to print memory addresses,
    // but we can demonstrate that i is passed by reference
    writeln("reference:", __primitive("_wide_get_addr", i));
}

zeroval doesn’t change the i in main, but zeroptr does because it has a reference to the variable.

To run the program, save it as references.chpl and use the Chapel compiler:

$ chpl references.chpl -o references
$ ./references
initial: 1
zeroval: 1
zeroptr: 0
reference: 140732920764416

In Chapel, references are similar to pointers in other languages, but they’re safer and more convenient to use. The ref keyword is used to pass arguments by reference, allowing functions to modify the original variables.