It seems pure ain't so pure after all
Don Clugston
dac at nospam.com
Tue Oct 2 00:38:56 PDT 2012
On 01/10/12 07:40, Tommi wrote:
> import std.stdio;
>
> int pow2(int val) pure
> {
> if (__ctfe)
> return 6;
> else
> return val * val;
> }
>
> void main()
> {
> assert(pow2(3) == 9);
> static assert(pow2(3) == 6);
>
> writeln("9 = 6 ... I knew it! '6' was faking it all along");
> readln();
> }
You don't need the if (__ctfe) to show this behaviour. Nor do you even
need CTFE at all (though it would be a bit less obvious). You could
demonstrate it in C++ too.
Any code that behaves differently when compiled with -O, will do this as
well. Constant folding of floating point numbers does the same thing, if
the numbers are represented in the compiler in a different precision to
how the machine calculates them. I believe that GCC, for example, uses
very much higher precision (hundreds of bits) at compile time.
More information about the Digitalmars-d
mailing list