Search⌘ K

Compile Time Function Execution (CTFE)

Explore how D's Compile-Time Function Execution allows functions to run at compile time, enhancing program efficiency. Understand use cases, limitations, and the __ctfe variable for conditional execution during compilation versus runtime.

Compile-time function execution

In many programming languages, computations that are performed at compile time are very limited. Such computations are usually simple like calculating the length of a fixed-length array or simple arithmetic operations:

writeln(1 + 2);

The 1 + 2 expression above is compiled as if it has been written as 3; there is no computation at runtime.

D has CTFE, which allows any function to be executed at compile time as long as it is possible to do so.

Let’s consider the following program ...