Compile-time function execution: Difference between revisions

Content deleted Content added
Line 42:
The use of <code>const</code> tells the compiler that the initializer for the variables must be computed at compile time<ref>[http://www.digitalmars.com/d/1.0/attribute.html#const D 1.0 language specification: Attributes]</ref>.
 
CTFE can be used to populate simple data structures at compile-time in a simple way (D 1version code,2) the(this <code>~</code>is operatora concatenatesfunction arrays and items to arraystemplate):
 
<source lang="D">int[N] genFactorials(int N)() {
int[N] result;
int[] genFactorials(int n) {
intresult[0] result= 1;
forforeach (i; n1 >=.. 0; --nN)
result[i] = factorial(n)result[i ~- result1] * i;
return result;
}
 
enum auto factorials = genFactorials!(13)();
const int N = 13;
static const auto factorials = cast(int[N])genFactorials(N - 1);
 
// Now 'factorials' contains at compile-time: