Pointers in Lisp

(defun zeroval (ival)
  (setf ival 0))

(defun zeroptr (iptr)
  (setf (car iptr) 0))

(defun main ()
  (let ((i 1))
    (format t "initial: ~a~%" i)

    (zeroval i)
    (format t "zeroval: ~a~%" i)

    (zeroptr (list i))
    (format t "zeroptr: ~a~%" i)

    (format t "pointer: ~a~%" (list i))))

(main)

Lisp supports the concept of pointers, although it’s not as explicit as in some other languages. In Lisp, we can use cons cells or lists to simulate pointer-like behavior.

In this example, we’ve created two functions: zeroval and zeroptr. The zeroval function takes a value and attempts to set it to zero, while zeroptr takes a list (simulating a pointer) and sets its first element to zero.

The zeroval function doesn’t actually modify the original value because Lisp uses pass-by-value for simple data types. However, zeroptr can modify the value because it’s working with a list, which is passed by reference.

In the main function:

  1. We initialize i to 1 and print its initial value.
  2. We call zeroval with i, but this doesn’t change i’s value in the main function.
  3. We call zeroptr with a list containing i. This effectively changes the value of i.
  4. Finally, we print the “pointer” by creating a list with i. In Lisp, this is analogous to getting the memory address of a value.

When you run this program, you should see output similar to:

initial: 1
zeroval: 1
zeroptr: 0
pointer: (0)

Note that Lisp doesn’t have explicit pointer syntax like & or *. Instead, we use lists to simulate pointer-like behavior. The concept of modifying values through references (like with zeroptr) is similar to using pointers in other languages.