Pointers in OCaml

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.

(* We'll show how references work in contrast to values with
   two functions: zeroval and zeroptr. zeroval takes 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. *)
let zeroval ival =
  let _ = ival in
  ()

(* zeroptr in contrast takes an int ref parameter, which is
   similar to an int pointer. The ! operator in the function
   body then dereferences the reference to get its current value.
   Assigning a value to a dereferenced reference changes the
   value at the referenced address. *)
let zeroptr iref =
  iref := 0

let () =
  let i = ref 1 in
  Printf.printf "initial: %d\n" !i;

  zeroval !i;
  Printf.printf "zeroval: %d\n" !i;

  (* The & operator is not needed in OCaml as i is already a reference *)
  zeroptr i;
  Printf.printf "zeroptr: %d\n" !i;

  (* We can print the address of a reference using Obj.magic *)
  Printf.printf "reference: %d\n" (Obj.magic i)

In this OCaml version:

  1. We use ref to create a mutable reference, which is similar to a pointer in other languages.
  2. The ! operator is used to dereference a reference (get its value).
  3. The := operator is used to assign a new value to a reference.
  4. We don’t need an explicit & operator to get the address of a value, as i is already a reference.
  5. 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.

$ ocaml pointers.ml
initial: 1
zeroval: 1
zeroptr: 0
reference: 140724063506672

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.