If I understand const right...

cy via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Mar 23 13:52:22 PDT 2016


a = a + 1

a is const, a + 1 is const, yet a can't be assigned to a + 1. And 
I think the reason is like...

const(int) a = 23;
while(something()) {
   a = a + 1;
}

in the first iteration, a is set to 23, and the value of "a + 1" 
is 24, but where is the computer gonna store that 24? It can't 
store it where 23 is, because that's constant data. In a register 
variable? What about the next iteration? A runtime queue of 
previously calculated consts that builds up with each iteration?

...not gonna happen. So since there's nowhere to store that 24 
(without some non-const variable to store it in), you can't point 
"a" at the new address, even if 24 itself would fit inside 
another constant bit of memory just fine.

I'm actually used to the runtime queue thing, from scheme and the 
like. "a = a + 1" allocates a new bit of memory, made immutable 
and never changed from then on, storing "a + 1" in it and 
pointing a at it. And if "a + 1" has already been calculated, it 
finds that old value and reuses it.

So I think that's why you can't assign to a constant variable, is 
that there's no locating/initializing of new constant memory on 
the fly, to have a place to put that 24, 25, etc. Variables, even 
mutable variables, always have the same address, and any of us 
who are confused can think of assigment as a storage operation, 
more like erlang's "=>" rather than scheme's "(let)".

To "change" an address, you have to use a mutable pointer (or the 
like). The variable will always have the same address, but 
there's a second address stored at that address, and since the 
storage is mutable, that second address can be changed, by 
mutating the memory stored at the first address.

So like...

const(int)[2] a = [23,24];
const(int)* b = a;
writeln(&a," always constant");
writeln(a, " always constant");
writeln(a[0]," always constant");
writeln(&b," always constant");
writeln(b," always mutable");
writeln(*b, "constant");
b = b + 1;
writeln(*b, "also constant, but a different one.");

something like that...


More information about the Digitalmars-d-learn mailing list