Constant Folding

Expressions with constant operands can be evaluated at compile time, thus improving run-time performance and reducing code size by avoiding evaluation at compile-time.

Example:

In the code fragment below, the expression (3 + 5) can be evaluated at compile time and replaced with the constant 8.

int f (void)
{
  return 3 + 5;
}
  

Below is the code fragment after constant folding.

int f (void)
{
  return 8;
}
  

Notes:

Constant folding is a relatively easy optimization.

Programmers generally do not write expressions such as (3 + 5) directly, but these expressions are relatively common after macro expansion and other optimizations such as constant propagation.

All C compilers can fold integer constant expressions that are present after macro expansion (ANSI C requirement). Most C compilers can fold integer constant expressions that are introduced after other optimizations.

Some environments support several floating-point rounding modes that can be changed dynamically at run time. In these environments, expressions such as (1.0 / 3.0) must be evaluated at run-time if the rounding mode is not known at compile time.