Optimisation: What is Constant Folding

One of the simplest things a compiler can do is to take constant expressions within your code and evaluate them at compile time. This is the essence of Constant Folding.

If you have “int i = 90 + 10”, the compiler can change that to “int i = 100” at compile time to save an add instruction for every invocation.

The name “Constant Folding” comes from how this process can be applied recursively. For example:

int func()
{
return 4 + 10;
}

int main()
{
int j = 100 + 10 + func();
}

In this example, func() can have its return changed to “return 14” and then where func() is called can be changed to “int j = 110 + func()” and then reduced to “int j = 110 + 14” and then “int j = 124”. Removing the constant function call entirely.