`static` symbol needs to be `immutable` for compile-time access?

Shriramana Sharma via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jan 22 01:56:27 PST 2016


Hello. This is a minimal abstraction of a part of my program:

int func(string s)
{
    static int [] i = [5, 6, 7];
    return i[2];
}
template temp(string s) { enum temp = func(s); }
void main() { static assert(temp!"str" == 7); }

With the above code I get:

<src>(4): Error: static variable i cannot be read at compile time
<src>(6):        called from here: func("str")
<src>(7): Error: template instance <src>.temp!"str" error instantiating

I find that if I either replace `static` by `immutable` or even just *add* 
`immutable` after `static`, the error goes away. Do all values which need to 
be readable at compile time need to be declared `immutable`?

In C/C++ the `static` here is used to avoid the array being created every 
time the function is entered; in D too it does the same thing, no? So if I 
have an array of constants in a function that I need to be accessible to a 
template at compile time, and I (for obvious reasons) don't want to be 
initialized at every function call, do I have to declare it `static 
immutable`?

-- 
Shriramana Sharma, Penguin #395953


More information about the Digitalmars-d-learn mailing list