Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 36 ยท Mixins and Metaprogramming

Compile-Time Function Execution (CTFE) in D

Learn D compile-time function execution: how ordinary functions run during compilation, enum and static initializers, lookup tables, limits, and a constexpr C stand-in.

One of D's most distinctive features is compile-time function execution, usually shortened to CTFE. The compiler contains an interpreter. When a value is needed at compile time, for example to size an array or initialize an enum, the compiler simply runs your function and uses the result. You do not write a separate template language: the same code runs at compile time or at run time.

D code is read-only on this site. The C stand-ins use constexpr, static_assert and the preprocessor, which are far more limited but demonstrate the same payoff: work done before the program starts.

Forcing compile-time evaluation

D
int factorial(int n)
{
    return n <= 1 ? 1 : n * factorial(n - 1);
}

enum f10 = factorial(10);          // computed while compiling
static immutable f5 = factorial(5);
static assert(factorial(4) == 24); // checked while compiling

void main()
{
    int x = factorial(6);           // run time (not forced)
    writeln(f10);                   // just prints a constant
}

A call is evaluated at compile time when its result is required in a compile-time context: an enum initializer, a static or module-level immutable initializer, a template argument, an array length, a static assert or a static if. In ordinary code like int x = factorial(6) the compiler may optimize but is not obliged to.

No special function keyword is needed. If a function uses only things the interpreter can handle, it works in both worlds.

What a CTFE function may do

CTFE supports most of D: loops, recursion, local arrays and associative arrays, structs, classes created and used inside the evaluation, string handling, and standard library functions that do not touch the outside world. It cannot:

  • read or write files or the console (no writeln at compile time; use pragma(msg, ...)),
  • call C functions or use inline assembly,
  • keep state that outlives the evaluation, or read mutable global variables,
  • use pointer tricks that break memory safety rules.

If the interpreter hits something unsupported, the compiler reports exactly why, pointing at the line inside your function.

Lookup tables at compile time

The classic use is building a table so the program does no work at startup:

D
ubyte[256] makeParityTable()
{
    ubyte[256] t;
    foreach (i; 0 .. 256)
    {
        int bits, v = i;
        while (v) { bits += v & 1; v >>= 1; }
        t[i] = cast(ubyte)(bits & 1);
    }
    return t;
}

immutable parity = makeParityTable();   // built at compile time

bool isOddParity(ubyte b) { return parity[b] != 0; }

The 256 entries are baked into the executable's data segment. Nothing is computed when the program runs.

A C stand-in: pay at build time

C23 constexpr objects and static_assert are evaluated by the compiler. C cannot run a loop at compile time, so the table here is written with a macro that expands to constants; the point is that the check proves the table right.

C Stand-in: constants and checks computed at compile time

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Parsing at compile time

Because strings work in CTFE, you can parse a domain-specific language while compiling. Paired with a string mixin, a function can turn a text description into real D code:

D
string makeStruct(string description)   // "Point: int x, int y"
{
    // split on ':' and ',' and build "struct Point { int x; int y; }"
    // ... ordinary string code ...
    return result;
}

mixin(makeStruct("Point: int x, int y"));

The standard library's std.regex.ctRegex uses exactly this idea: it compiles a regular expression into specialized D code during compilation.

Compile time or run time?

You can ask at run time of the same function which world it is in:

D
int work(int n)
{
    if (__ctfe)
    {
        // slower but interpreter-friendly path
    }
    return n * 2;
}

__ctfe is true only while the compiler is evaluating the function. Use it sparingly, for example to skip a faster algorithm that needs pointer tricks.

Costs and cautions

  • The interpreter is slower than compiled code and uses memory. A heavy CTFE job can make builds take longer; measure with the compiler's -v option.
  • Results are cached only per evaluation, so a function called with the same arguments in many places runs each time. Store the result in an enum or immutable once and reuse it.
  • Keep CTFE functions pure (pure marks them as having no side effects), which also makes them easy to reason about and test.
  • Test them twice: with static assert (compile time) and in a unittest (run time) so both paths agree.
C Stand-in: verifying a table against run-time computation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

This is the "test both paths" habit in miniature: the table is built at compile time, the reference value at run time, and they must agree.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which of these forces a function call to run at compile time?

    An enum initializer must be a compile-time value, so the compiler runs f in its interpreter.
  2. 2. Which operation is NOT possible in CTFE?

    CTFE cannot do I/O. Use import("file") for compile-time file contents.
  3. 3. How do you print a compile-time value while compiling?

    pragma(msg, ...) prints during compilation.
  4. 4. What does __ctfe tell you?

    It is true only during compile-time evaluation.

Summary

  • The compiler interprets ordinary D functions when a compile-time value is needed.
  • enum, static immutable, template arguments and static assert trigger CTFE.
  • No I/O, no C calls; use pragma(msg, ...) and import("file") instead.
  • Build lookup tables and parsers at compile time; test both compile-time and run-time results.

Next: Traits and static if