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.
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.
Here’s how we use these functions:
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:
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.