# Ch 21: Global Variables

> Study guide to Crafting Interpreters chapter 21. Statements and global variables in clox: print and expression statements, declarations, global variable get…

Updated October 20, 2026.

## Summary {#summary}

Crafting Interpreters chapter 21, Global Variables: Statements and global variables in clox: print and expression statements, declarations, global variable get and set via the hash table, and assignment with correct precedence. Budget about 5 hours; the book's `chap21_global` tests check your code.

## Key facts {#key-facts}

- Week 19 of 145 on the cracked.guide path, in [Crafting Interpreters](https://cracked.guide/crafting-interpreters).
- Time budget: about 5 hours.
- Part of the book: clox (bytecode VM, C).
- Verified on cracked.guide when the official `chap21_global` tests pass on GitHub Actions.
- 3 challenges at the end of the chapter.

## Week 19 goals {#objectives}

By the end of week 19 you can:

- Implement print, expression and var statements in clox's compiler.
- Explain how canAssign rejects invalid targets like `a * b = c`.
- Trace OP_DEFINE_GLOBAL, OP_GET_GLOBAL and OP_SET_GLOBAL through the globals table.

## This week's steps {#steps}

- Read the chapter: Pay attention to how the canAssign flag prevents invalid assignment targets.
- Write the code in your lox repo: Type it into clox/ (C) yourself as you read, and get it running.
- Do the challenges (1–3): Challenge 1 (stop adding duplicate name constants) and challenge 2 (faster global lookup) are both good engineering exercises.
- Push and let the tests verify it: Your repo runs the book's chap21_global tests on every push; passing marks this done.

## Why it matters {#why}

Shows how a single-pass compiler handles declarations and l-values, a trickier problem than in jlox.

## How to approach it {#approach}

Pay attention to how the canAssign flag prevents invalid assignment targets. Test with expressions like a * b = c.

## Challenges {#challenges}

3 challenges at the end of the chapter.

Challenge 1 (stop adding duplicate name constants) and challenge 2 (faster global lookup) are both good engineering exercises. Challenge 3 (REPL-friendly forward references) is a design puzzle.

## Common traps {#traps}

- Invalid assignment targets silently accepted when canAssign is not threaded through correctly.

## Links {#links}

- [Read the chapter: Ch 21: Global Variables](https://craftinginterpreters.com/global-variables.html)
- [Official repo: book source, both interpreters, test suite](https://github.com/munificent/craftinginterpreters)
- [Running the official test suite against your own interpreter (repo README)](https://github.com/munificent/craftinginterpreters#testing-your-implementation)

---

Source: https://cracked.guide/guide/ci-21
cracked.guide: A free, dated 145-week path to getting genuinely cracked at programming.
