It seems pure ain't so pure after all

Jonathan M Davis jmdavisProg at gmx.com
Sun Sep 30 23:48:39 PDT 2012


On Sunday, September 30, 2012 23:38:43 Jonathan M Davis wrote:
> On Monday, October 01, 2012 08:25:39 Tommi wrote:
> > Thus we're in a situation where pure means pure only by
> > convention, not because it's enforced by the compiler. It's like
> > const in c++ then, it's const only by convention, only because
> > people promise that they're not going to mutate it. I don't like
> > rules that are enforced only by everybody relying on good manners.
> 
> No. We're not in that situation at all. The function will do the same thing
> with every call at compile time, and it will do the same thing with every
> call at runtime. It's like you're complaining about the fact that a
> function on a big endian machine doesn't do exactly the same thing as when
> it's compiled for a little endian machine. It's being compiled for a
> different environment, so its behavior can change. __ctfe really isn't all
> that different from static if or version blocks which effectively result in
> different functions depending on how or where the code is compiled.
> 
> What isn't enforced is that the function does the same thing at compile time
> as at runtime, and you can't enforce that any more than you can enforce
> that it does the same thing on one machine as another when they have
> different architectures or OSes or whatot. By using __ctfe, you are
> providing an alternate implementation for compile time just like you could
> provide alternate implementations for different OSes or architectures.

While __ctfe is not used in a static if, that's effectively the behavior that 
it has. You're basically complaining about how these two functions don't 
return the same value:

static if(__ctfe)
{
    int pow2(int val) pure
    {
        return 6;
    }
}
else
{
    int pow2(int val) pure
    {
        return val * val;
    }
}

They're effectively completely different functions that share the same name (and 
presumably the same intent), but they're implementations are different, and 
it's obviously up to the programmer to make sure that they do what they're 
supposed to do. It has _nothing_ to do with pure.

- Jonathan M Davis


More information about the Digitalmars-d mailing list