sicp.io
5.5.6 · Compiled variable access

A lexical address replaces a name search with two indexes.

A compiler can encode a variable as a frame depth and binding offset, allowing the machine to fetch its value directly from the runtime environment.

Guiding question

What environment knowledge can compilation move out of runtime lookup?

  • Represent a lexical address as frame depth and binding offset
  • Select a runtime frame without inspecting variable names
  • Select one value slot inside that frame
  • Connect compile-time name search to runtime direct lookup

The address (depth offset) counts outward through environment frames, then across one frame. lexical-ref follows only those two numbers. The runtime frames contain values rather than name-value pairs, so no assoc or symbol comparison occurs during the fetch.

find-address performs the name search against the compiler environment, whose frames contain variable names. Once it produces (1 0) for x, the runtime can use that address to fetch 42 from matching value frames. The example makes the compiler and machine agree on one frame layout.

SICP code438 of 1,048,576 UTF-8 bytes
Examples
Result
Output
Value
Diagnostic
Execution trace0 / 0 events
    Programs run in the browser with their result and execution trace.
    Expected result

    The first program returns (20 30 50). The second resolves x to address (1 0), then returns ((1 0) 42).

    Trace focus

    In the first run, follow depth recursion separately from list-ref offset selection and confirm that no variable symbol is searched. In the second run, separate the compile-environment name search from the later value-frame lookup.

    Try it yourself

    Change the program and compare the result.

    Add w after z in the innermost compile-time frame and add 11 to the matching runtime frame. Predict the address and value of w.

    Show hint

    The innermost frame has depth 0. Its second slot has offset 1.

    Complete this lesson

    0 of 23 lessons complete in this chapter0%