OCaml supports references, which are similar to pointers in other languages. They allow you to create mutable values and pass them around in your program.
In this OCaml version:
We use ref to create a mutable reference, which is similar to a pointer in other languages.
The ! operator is used to dereference a reference (get its value).
The := operator is used to assign a new value to a reference.
We don’t need an explicit & operator to get the address of a value, as i is already a reference.
To print the “address” of a reference, we use Obj.magic, which is not recommended in production code but serves our purpose here for demonstration.
When you run this program, you’ll see that zeroval doesn’t change the i in the main function, but zeroptr does because it has a reference to the mutable value.
Note that the exact reference value may differ on your system.
In OCaml, references are used less frequently than in languages like C or Go, as OCaml encourages a more functional programming style. However, they are available when mutable state is needed.