Constant folding and propagation are typically used together to achieve many simplifications and reductions, and their interleaved, iterative application continues until those effects cease. Consider this unoptimized pseudocode returning a number unknown pending analysis: int a = 30; int b = 9 - (a / 5); int c = b * 4; if (c > 10) { c = c - 10; } return c * (60 / a); Applying constant propagation once, followed by constant folding, yields: int a = 30; int b = 3; int c = b * 4; if (c > 10) { c = c - 10; } return c * 2; Repeating both steps twice produces: int a = 30; int b = 3; int c = 12; if (true) { c = 2; } return c * 2; Having replaced all uses of variables a and b with constants, the compiler's
dead-code elimination applies to those variables, leaving: int c = 12; if (true) { c = 2; } return c * 2; (Boolean constructs vary among languages and compilers, but their details—such as the status, origin, and representation of
true—do not affect these optimization principles.) Traditional constant propagation produces no further optimization; it does not restructure programs. However, a similar optimization,
sparse conditional constant propagation, goes further by selecting the appropriate conditional branch, and removing the always-true conditional test. Thus, variable c becomes redundant, and only an operation on a constant remains: return 4; If that pseudocode constitutes a function body, the compiler knows the function evaluates to integer constant 4, allowing replacement of calls to the function with 4, and further increasing program efficiency. == See also ==