immutable int n = Test(); int[n] x;---- compiles, but __ctfe is false. How?

Ali Çehreli acehreli at yahoo.com
Fri Feb 21 09:04:45 PST 2014


On 02/21/2014 08:46 AM, Gopan wrote:

 > On Friday, 21 February 2014 at 14:04:45 UTC, FreeSlave wrote:
 >> Another strange thing:
 >>
 >> import std.stdio;
 >>
 >> uint Test()
 >> {
 >>     if (!__ctfe)
 >>     {
 >>         return 3;
 >>     }
 >>     return 2;
 >> }
 >>
 >>
 >>
 >> void main()
 >> {
 >>     immutable n = Test();
 >>     int[n] arr;
 >>     writeln("arrary length = ", arr.length, " ; n = ", n);
 >> }
 >>
 >> Output:
 >> arrary length = 2 ; n = 3
 >>
 >> When you think about it you understand that it's logically right
 >> behavior, but it's not acceptable in practice.
 >
 > It looks like 'immutable n = Test();' is executed during both compile
 > time and runtime.  Is that what is happening?

Yes. The compiler needs the value of n at compile time so it evaluates 
it at compile time.

I agree that it is confusing but I feel like it is the responsibility of 
the programmer to ensure consistent behavior.

Ali



More information about the Digitalmars-d-learn mailing list