immutable int n = Test(); int[n] x;---- compiles, but __ctfe is false. How?
anonymous
anonymous at example.com
Fri Feb 21 06:14:13 PST 2014
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();
As this is a local variable, this is a runtime initialization, no
__ctfe here. Doesn't matter that it's immutable. It's
static/global vs local. So, this correctly does ++counter.
Make it static immutable n, and counter won't be incremented.
> int[n] arr;
Not sure if this should compile. n is a run-time value. It just
happens that it can be CTFE'd. A more problematic case:
---
void main()
{
immutable n = __ctfe ? 1 : 2;
int[n] a;
assert(a.length == n); // fails, wat
}
---
> 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
More information about the Digitalmars-d-learn
mailing list