Global const variables

Solomon E via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Oct 21 05:08:33 PDT 2014


On Tuesday, 21 October 2014 at 08:48:09 UTC, safety0ff wrote:
> On Tuesday, 21 October 2014 at 08:25:07 UTC, bearophile wrote:
>> Minas Mina:
>>
>>> Aren't pure functions supposed to return the same result 
>>> every time? If yes, it is correct to not accept it.
>>
>> But how can main() not be pure? Or, how can't the 'a' array be 
>> immutable?
>>
>> Bye,
>> bearophile
>
> There can exist a mutable reference to a's underlying memory:
>
> const int[] a;
> int[] b;
>
> static this()
> {
>     b = [1];
>     a = b;
> }

`a` isn't a reference to `b`. `a` is assigned by value and has 
its own storage. You could change its type to const int[]* a = 
&b; then it would be a reference to mutable storage. I made an 
example program to figure these things out, or else I wouldn't 
know what I'm talking about.

import std.stdio;
import std.conv;

const int[] a;
int[] b;

static this()
    {
         string entry;
         while(entry == "") {
             try {
                 write("enter an int: ");
                 entry = readln();
                 b = [to!int(entry[0..entry.length-1])];
             } catch(ConvException e) {
                 writeln("error, try again");
                 entry = "";
             }
         }
         a = b;
     }

int[] x = [0,1,2,3];

class Holder
{
     const(int[]) y;
     this() { y = x; }
}

void main()
{
     auto H = new Holder();
     writeln("original const a ", a); // [the int that was entered]
     b = [8,7];
     writeln("unaltered const a ", a); // [the int that was 
entered]
     x = [10,9];
     writeln("unaltered const member y ", H.y); // [0, 1, 2, 3]
     H = new Holder();
     writeln("new const member y ", H.y); // [10, 9]
     writeln("immutable m ", get_m()); // [42]
}

immutable int[] m = [42];

immutable(int[]) get_m() pure
{
     return m;
}



More information about the Digitalmars-d-learn mailing list