ctfe and static arrays

anonymous via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun May 24 14:14:54 PDT 2015


On Sunday, 24 May 2015 at 20:53:03 UTC, Jay Norwood wrote:
> On Sunday, 24 May 2015 at 18:14:19 UTC, anonymous wrote:
[...]
>> 1) static int[5] x; -- x is a static variable with a static 
>> array type
>> 2) static int[] x; -- static variable, dynamic array
>> 3) int[5] x; -- non-static variable, static array
>> 4) int[] x; -- non-static variable, dynamic array
>>
>> So, CTFE can't handle examples 1 and 2, because they're static 
>> variables. 3 and 4 are fine.
>
> From your description, I would expect this to fail since I 
> would expect it to be included in 2 above, but it builds and 
> prints ok.
>
> import std.stdio;
>
> struct A {  int me;   int next;   int prev;}
>
> A[] initA(int n)
> {
> 	if (!__ctfe){
> 		assert(false);
> 	}
> 	A[] v = new A[n];
> 	foreach (i; 0..n){
> 		v[i].me = i;
> 		v[i].prev = i-1;
> 		v[i].next = i+1;
> 	}
> 	return v;
> }
>
> int main(string[] argv)
> {
>
> 	enum int N = 100;
> 	static A[] linkedA = initA(N);

I'm guessing you mean that this line would fall under case 2.

Only the right hand side, i.e. initA(N), is done in CTFE here. 
The result is then used to initialize linkedA -- that step is not 
CTFE anymore. You're not referencing any static variable in 
initA, so everything's fine.


More information about the Digitalmars-d-learn mailing list