Jump to content

Compile-time function execution

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by IamOz (talk | contribs) at 23:37, 10 April 2007 (Created page with 'Compile time function execution (CTFE) is the ability of a compiler, that would normally compile a function to machine code and execute it at run time, to execu...'). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

Compile time function execution (CTFE) is the ability of a compiler, that would normally compile a function to machine code and execute it at run time, to execute the function at compile time. This is possible if the arguments to the function are known at compile time, and the function does not make any reference to or attempt to modify any global state.

Example 1

This example code is in the D programming language:

int square(int x)
{
   return x * x;
}

const int y = square(3);  // y is set to 9 at compile time

Example 2

In C++, template metaprogramming is often used to compute values at compile time, such as:

template <int N>
struct Factorial 
{
    enum { value = N * Factorial<N - 1>::value };
};

template <>
struct Factorial<0> 
{
    enum { value = 1 };
};

// Factorial<4>::value == 24
// Factorial<0>::value == 1
void foo()
{
    int x = Factorial<4>::value; // == 24
    int y = Factorial<0>::value; // == 1
}

With compile time function evaluation, the code used to generate the factorial would be exactly the same as what one would write for run time evaluation (example is in D):

int factorial(int n) 
{
    if (n == 0)
       return 1;
    return n * factorial(n - 1);
}

void foo()
{
    static const int x = factorial(4); // == (4 * 3 * 2 * 1) == 24
    static const int y = factorial(0); // == 0! == 1
}

The use of static const tells the compiler that the initializer for the variables must be computed at compile time.