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

Marc Schütz via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jan 22 03:36:41 PST 2016


On Friday, 22 January 2016 at 10:15:19 UTC, Mike Parker wrote:
> A static variable is still a runtime variable. It's effectively 
> the same as declaring a variable outside of the function scope 
> at module scope, except that it's visible only in the current 
> scope and the function name gets mangled into the symbol
>
> int i;
>
> void foo() {
>    static int j;
> }
>
> j is no more a compile-time value than i is. If you want an 
> array of constant values available at compile-time, then you 
> need to declare the array as immutable.

To expand on this:

As you noted, a `static` local variable is, with regards to its 
lifetime, effectively global. This means there could be code like 
the following:

     int func(string s)
     {
         int [] i = [5, 6, 7];
         auto result = i[2];
         i[2] = 42;
         return result;
     }

I.e., the array could contain a different value depending on 
whether the function has already been run before. Functions 
evaluated at compile time need to be effectively pure, because 
the order of declarations in D is specified not to matter (modulo 
bugs). Making the variable immutable, or turning it into a normal 
local variable (even a mutable one!), guarantees that.


More information about the Digitalmars-d-learn mailing list