static variables for non-constant expressions?

Jonathan M Davis jmdavisProg at gmx.com
Sun Apr 10 18:37:37 PDT 2011


> I was wondering why static variables can't have a run-time initializer.
> 
> For example this won't compile:
> void foo(int input)
> {
>     static x = input;
> }
> 
> But you can do it manually:
> void bar(int input)
> {
>     static bool initted;
>     static typeof(input) x;
>     if (!initted) { x = input; initted = true; }
> }
> 
> It's quite a bit more ugly. You also have to expand this for every new
> static variable that you write.
> 
> I don't know the background of how static variables really work, so is
> there a good reason why the first function can't work like the one below
> it?

They have to be calculated at compile time so that ordering doesn't matter. If 
the order mattered, then you get into dependency problems or risk using 
undefined variables. Languages like C++ and Java have problems with that. By 
forcing all module level variables, member variables, and static variables (be 
they class variables or local variables) to have their initializers be static, 
it avoids the order problem completely. In all cases except for local static 
variables, you can use the appropriate constructor if you need to do the 
initialization at runtime. For static local variables, you'd have to use 
another static local variable which indicated whether the first had been 
initialized yet or not.

In any case, by forcing all variables other than non-static local variables to 
have their direct initializers be determined at compile time avoids dependency 
problems which often result in undefined behavior in other languages.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list