Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

What You Want

Name: Anonymous 2013-06-07 20:15

What you want, but have never been able to put into words, is a "two-phase" C compiler.  You want compile-time C code that outputs run-time C code.

Example: Factorial function.

Naive C approach:


int factorial(int n)
{
    int i, x = 1;
    for (i = 2; i <= n; ++i) x *= i;
    return x;
}


Realization - This code is inefficient and pointless.  On 32-bit systems, passing anything larger than 12 into this function will fail.  Even with 64-bit integers, the largest acceptable value is 20.

Optimized C approach:


int factorial(int n)
{
    int f[] = { 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600 };
    return f[n];
}


Problem - The optimized function is less readable.  Calculating a factorial is a repetitive process by its nature, and we have obfuscated that for the sake of efficiency.  Further, we had to spend our precious time calculating the results for every possible input.  This would be unacceptable for most functions.

Solution - The "Two-Phase C" approach:


out <<END_TEXT
int factorial(int n)
{
    int f[] =
    {
        1
END_TEXT

int i, j = 1;
for (i = 1; i <= 12; i++)
{
    out ",";
    j *= i;
    out j;
}

out <<END_TEXT
    };
    return f[n];
}
END_TEXT


Obviously, the output of this "first-phase C" code is the "optimized C approach," shown above.  It is now explicit to the maintainer of the code how the factorial is being calculated, even though no factorial calculation needs to be performed at run-time.  Congratulations.

Name: Anonymous 2013-08-31 9:23



ちなみに

誤:海鮮問屋
正:廻船問屋

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List