diff --git a/hands-on_dlang.md b/hands-on_dlang.md index b98156b..97f1c44 100644 --- a/hands-on_dlang.md +++ b/hands-on_dlang.md @@ -1371,3 +1371,45 @@ assert(c == 5); immutable runTimeString = q{int c =5;}; mixin(runTimeString); // compile error, runTimeString is not known at compile-time ``` + +### Compile Time Function Evaluation (CTFE) + +In D, it is possible to execute functions at compile time. This is triggered on +the call site, i.e. whenever a function is called in a context where the result +needs to be known at compile time, the function will be evaluated at compile +time. Some of those contexts are: +* Template parameters +* Initialization of `static` variables +* Definition of `enum`s (i.e. compile time constants) +* `static assert`, `static foreach` and `static if` +* Template constraints + +There are some limitations to what a function executed at compile time may do. +Essentially, the functions need to be *pure* in some sense, i.e. they may not +have side effects such as IO. + +```D +import std.stdio : writeln; + +auto sqrt(T)(T x) { + enum GoodEnough = 0.01; + import std.math : abs; + T z = x*x, old = 0; + int iter; + while (abs(z - old) > GoodEnough) { + old = z; + z -= ((z*z)-x) / (2*z); + } + + return z; +} + +void main() { + double n = 4.0; + writeln("The sqrt of runtime 4 = ", + sqrt(n)); + static cn = sqrt(4.0); // calculated at compile time + writeln("The sqrt of compile time 4 = ", + cn); +} +``` \ No newline at end of file