D's treatment of values versus side-effect free nullary functions

Jim Balter Jim at Balter.name
Mon Jul 26 17:30:24 PDT 2010

"Rainer Deyke" <rainerd at eldwood.com> wrote in message 
news:i2jeja$1lha$1 at digitalmars.com...
> On 7/25/2010 13:41, Jim Balter wrote:
>> But there are
>> (at least) two problems: 1) you can't be certain that the code will be
>> run at run time at all -- in generic code you could easily have function
>> invocations with constant values that would fail in various ways but the
>> function is never run with those values because of prior tests.
> That's a good point - but at the same time, I'm having trouble thinking
> of any sensible example where this would be an issue.

Consider some code that calls a pure function that uses a low-overhead 
exponential algorithm when the parameter is small, and otherwise calls a 
pure function that uses a high-overhead linear algorithm. The calling code 
happens not to be CTFEable and thus the test, even though it only depends on 
a constant, is not computed at compile time. The compiler sees two calls, 
one to each of the two functions, with the same parameter passed to each, 
but only one of the two will actually be called at run time. Trying to 
evaluate the low-overhead exponential algorithm with large parameters at 
compile time would be a lose without a timeout to terminate the attempt. It 
might be best if the compiler only attempts CTFE if the code explicitly 
requests it.

> It would require
> at all of the following factors:
>  - The function itself is a candidate for CTFE.
>  - The arguments to the function can be evaluated at compile time, but
> are not simple constants (i.e. they depend on template parameters).
>  - The code that calls the function depends on run-time parameters.
>  - The function is never called with parameters that prevent it from
> terminating, but the compiler is unable to determine that this is the 
> case.
> Something like this would work, I guess, but it's horribly contrived:
> int terminate_if_nonzero(int i) {
>  return (i != 0) ? i : terminate_if_nonzero(i);
> }
> void f(int i)(bool call_it) {
>  if (call_it) terminate_if_nonzero(i);
> }
> bool get_input_and_return_false() {
>  // This function is not a CTFE candidate because it performs I/O.
>  read_input();
>  return false;
> }
> void main() {
>  f!(0)(get_input_and_return_false());
> }
> -- 
> Rainer Deyke - rainerd at eldwood.com 

More information about the Digitalmars-d mailing list