On Friday, 21 February 2014 at 13:38:58 UTC, Gopan wrote:
Attempting to learn CTFE, I tried the following test.

size_t counter;

uint Test()
{
        if (!__ctfe)
        {
                ++counter;// This code is for execution at run time
        }
        return 2;
}

void main()
{
        writeln("counter = ", counter);
        
        immutable int n = Test();
        int[n] arr;
writeln("arrary length = ", arr.length, " ; counter = ", counter);
}

output:
counter = 0
arrary length = 2 ; counter = 1

For array declaration to be successful, its size has to be known at compile time. The above code compiles too. But __ctfe seems to be false while performing Test().

Instead, if I write
        int[Test()] c;
        writeln("c.length = ", c.length, " ; counter = ", counter);
output is
counter = 0
c.length = 2 ; counter = 0

What is wrong in my mind?

Thanks,
Gopan

Use enum n = Test() or make immutable n global variable i.e. place it before main.

Reply via email to