Assigning global and static associative arrays

Jonathan M Davis jmdavisProg at gmx.com
Fri Aug 31 09:57:58 PDT 2012


On Friday, August 31, 2012 16:38:13 ixid wrote:
> Why does this not work:
> 
> int[string] dayNumbers =
> [ "Monday" : 0, "Tuesday" : 1, "Wednesday" : 2,
> "Thursday" : 3, "Friday" : 4, "Saturday" : 5,
> "Sunday" : 6 ];
> 
> void main() {
> //Stuff
> }
> 
> With the error 'non-constant expression'? This error also seems
> to prevent me making static associative arrays in functions
> elegantly.

Because they can't be declared at runtime like that. For that to work, they'd 
have to be constructable at compile time and then have the structure persist 
to runtime, and with all of the pointers and whatnot in an AA, that's far from 
trivial. The same occurs with classes. While you can use some of them in CTFE, 
you can't use them to directly initialize any variables whose values need to 
be known at compile time and persist until runtime.

You have to use static constructor to initialize the variable at runtime.

static this()
{
 //initialization code here...
}

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list