Error: non-constant expression...

Jonathan M Davis jmdavisProg at gmx.com
Fri Nov 26 14:29:03 PST 2010


On Friday 26 November 2010 11:16:08 spir wrote:
> Hello,
> 
> void f () {
>     static string[string] map = ["1":"un", "2":"du", "3":"tri"];
> }
> ==>
> Error: non-constant expression ["1":"un","2":"du","3":"tri"]
> 
> I do not understand what is meant, and what I should do. I need 'static',
> it's a constant value for the func. "static int[] a = [1,2,3];" is OK.
> Where's the difference?
> Also tried const() and immutable(), who knows?, but no way. Search does not
> bring anything for "non-constant expression". (Also: pointer to dmd error
> messages welcome.)

_All_ variables except for non-static local variables must have their 
initializers known at compile time. So, whatever you assign to them must be 
valid with CTFE.

At present, I don't believe that associative arrays are valid CTFE (hence the 
error). The run into the same problem as classes with regards to dynamic memory 
allocation at compile time. It will be fixed at some point, but it hasn't yet 
been fixed, so CTFE still disallows a number of constructs which it is supposed 
to eventually support.

So, you'll have to find a way to either initialize the variable at runtime or 
assign to it at runtime. Given that it's a local variable, you can't use a 
constructor of any variety to initialize it (with a global or class/struct 
variable you could use a static constructor, whereas with member variables, 
you'd use the constructor(s) for the type). So, you may have to do something 
unweildy like declare a second static local variable which is a bool which says 
whether or not map has been initialized. And if it hasn't then assign to it 
(which technically isn't an initialization, since it was initialized at compile 
time - it's just that it was initialized to null). Someone else may have a 
better suggestion though.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list