Global const variables

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Oct 21 09:52:12 PDT 2014


On Tuesday, October 21, 2014 08:02:50 bearophile via 
Digitalmars-d-learn
wrote:
> Currently this code gets rejected:
>
> const int[] a = [1];
> void main() pure {
>      auto y = a[0];
> }
>
>
> test2.d(3,14): Error: pure function 'D main' cannot access
> mutable static data 'a'
> test2.d(3,14): Error: pure function 'D main' cannot access
> mutable static data 'a'
>
> But is this a good idea? Isn't it better to accept it?

In principle, it should be fine, but because it's using const, it 
won't work.
global or static variables which are directly initialized with 
values that
cannot possibly have mutable references elsewhere in the code are 
the only
case where accessing const variables from outside a pure function 
like this
could work - i.e. the cases where immutable and const are 
essentially
identical (the only real difference being that if the variable is 
a reference
type, if it's immutable, it's also shared, whereas if it's const, 
it's
thread-local). So, I don't think that it's at all surprising that 
the compiler
rejects it. It should probably be made smarter so that it doesn't 
reject it,
but because you can just as easily make the variable immutable, 
you're not
losing any real functionality in the interim.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list