Error: non-constant expression...
bearophile
bearophileHUGS at lycos.com
Fri Nov 26 13:17:10 PST 2010
spir:
> 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.
Associative arrays are run-time things... well, enum associative arrays are compile-time things in theory, but there is a compiler bug here (I think an enum struct gets re-evaluated each time).
So this works, but I think it's not efficient:
void foo() {
enum string[string] map = ["1":"un", "2":"du", "3":"tri"];
}
> I need 'static', it's a constant value for the func.
A static variable in a function is a global value that is visible only inside that function and its sub-scopes (this is not always true in DMD, but I think these cases are bugs).
> "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".
Both const and immutable work:
void foo() {
immutable string[string] map1 = ["1":"un", "2":"du", "3":"tri"];
const string[string] map2 = ["1":"un", "2":"du", "3":"tri"];
}
But those map1 and map2 aren't static, this is not good because I think those AAs get initialized at each function call (despite only once is enough here). To avoid that you may use:
immutable string[string] fooMap;
static this() {
fooMap = ["1":"un", "2":"du", "3":"tri"];
}
void foo() {
// ....
}
But the disadvantage is that fooMap is accessible outside foo() too.
In my mind there is some confusion about all this. Other people may give you better answers.
> (Also: pointer to dmd error messages welcome.)
I don't know any complete list of DMD errors.
Bye,
bearophile
More information about the Digitalmars-d-learn
mailing list