Global variables read at compile time?
Justin Whear
justin at economicmodeling.com
Wed Aug 15 08:42:32 PDT 2012
On Wed, 15 Aug 2012 15:36:24 +0200, Stefan wrote:
> Hi there, I'm having trouble getting the following code to compile:
>
> import std.stdio;
>
> string a = "a";
> string b = a;
>
> void main()
> {
> writeln(b);
> }
>
> DMD spits out the error "test.d(4): Error: variable a cannot be read at
> compile time". Is there any way to tell the compiler I want b evaluated
> at runtime, or am I missing something obvious here?
D is not as context-sensitive as what you may be used to. This is a
feature to make the language more parseable and human-grokable.
Basically, the result of a module-level assignment should not depend on
what came before, so this example code is invalid:
string a = "a";
a = "b";
string b = a;
This would require the declaration of b to depend on the order of the
declarations/statements which come before it. When you add in the import
of modules, things would get really hairy really fast. So module-level
declarations must use constant expressions (literals or symbols to
constant data) in their initialization.
Justin
More information about the Digitalmars-d-learn
mailing list