Compile time function execution...

Nicolai Waniek no.spam at thank.you
Fri Feb 16 11:56:30 PST 2007


Walter Bright wrote:
> ... is now in DMD 1.006. For example:
> 
>> -------------------------------------------
>> import std.stdio;
>>
>> real sqrt(real x)
>> {
>>    real root = x / 2;
>>    for (int ntries = 0; ntries < 5; ntries++)
>>    {
>>        if (root * root - x == 0)
>>            break;
>>        root = (root + x / root) / 2;
>>    }
>>    return root;
>> }
>>
>> void main()
>> {
>>    static x = sqrt(10);   // woo-hoo! set to 3.16228 at compile time!
>>    writefln("%s, %s", x, sqrt(10));  // this sqrt(10) runs at run time
>> }
>> ------------------------------------------
> 
> This should obsolete using templates to compute values at compile time.


I didn't read the whole thread, but I just found some replies about how
to turn off/on the automatic compile time execution.

I would suggest, that the default behaviour will be "execute as much as
possible during compile time", but that there are two keywords (possibly
"runtime" and "compiletime") that will indicate what the method is, for
example:

runtime float sqrt()
{
   ...
}

That would expand to that the function is _not_ executed during compile
time, even if it would be able to.
On the other hand,

compiletime float sqrt()
{
   ...
}

Will be executed during compile time (as the standard). But as a
difference to the regular behaviour, a function declared as
"compiletime" that may not be executed during compile time may throw a
hint when compiling so that the developer may change it until there's no
hint left.

greetings
Nicolai



More information about the Digitalmars-d mailing list