Course contentsShow
← Computer Science
Lesson 2062 of 2,87246. Compilation and InterpretationFree lesson

Constant Propagation

Replacing variable references with their known constant values throughout the code.

Constant Propagation

What You'll Learn

You'll learn how compilers replace variable references with their known constant values to simplify code and enable further optimizations.

The Core Idea

Constant propagation takes what constant folding discovered—that certain variables hold constant values—and spreads that knowledge throughout your code. Instead of keeping a variable that never changes, the compiler substitutes the actual constant value everywhere that variable appears.

Think of it like someone constantly asking "What's the speed limit?" If you know it's always 55 mph on this road, you'd eventually just tell them "55" every time instead of saying "check the speedLimit variable."

How It Works

After the compiler performs constant folding to evaluate expressions at compile time, it tracks which variables hold constant values. Then it propagates (spreads) those constants forward through the code:

x = 14          // x is constant: 14
y = x + 3       // becomes: y = 14 + 3 (then constant folding → y = 17)
z = x * 2       // becomes: z = 14 * 2 (then constant folding → z = 28)
print(y)        // becomes: print(17)

The compiler replaces every use of x with 14, every use of y with 17, and so on. This creates a cascade effect: propagating one constant often reveals new opportunities for constant folding, which reveals more constants to propagate.

Benefits

Constant propagation eliminates variable lookups, reduces memory access, and exposes dead code (assignments to variables that are never actually used with varying values). It's particularly powerful when combined with other optimizations in the pipeline.

Key Takeaway: Constant propagation replaces variable references with their known constant values throughout the program, simplifying code and enabling additional compile-time optimizations.