If I understand const right...

ag0aep6g via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Mar 23 14:10:49 PDT 2016


On 23.03.2016 21:52, cy wrote:
> const(int)[2] a = [23,24];
> const(int)* b = a;

Should be: const(int)* b = a.ptr;

> writeln(&a," always constant");
> writeln(a, " always constant");

There's some subtlety here. `a` itself is not const, but its elements 
are. `a` being a fixed-sized array, you can't actually change anything 
when the elements are not mutable. Things would be different with a 
dynamic array.

> writeln(a[0]," always constant");
> writeln(&b," always constant");

The address of a local variable isn't exactly const/immutable in the 
sense of the type system, I think. It simply doesn't change during the 
run of the function, and afterwards it's not considered alive anymore.

> writeln(b," always mutable");
> writeln(*b, "constant");

Yup and yup.

> b = b + 1;

Just to be 100% clear: you're adding to the pointer here, not to the 
value that's being pointed at. It's 24, because that's the second item 
in `a`.

You can also allocate a whole new int and add set it to `*b + 1`. I 
think that's closer to your original goal.

----
b = new int(*b + 1);
----

> writeln(*b, "also constant, but a different one.");
>
> something like that...



More information about the Digitalmars-d-learn mailing list