Meaning of const variables

ketmar via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jun 20 19:54:06 PDT 2016


On Tuesday, 21 June 2016 at 02:24:03 UTC, jmh530 wrote:
> So the line from the spec is
> "Const types are like immutable types, except that const forms 
> a read-only view of data. Other aliases to that same data may 
> change it at any time."
>
> I tried making an alias of a const variable and modifying it, 
> but that didn't work. So presumably they mean something else.

yep, the spec was talking about data aliases in compiler 
terminology, not about D aliases. i.e. this is valid:

   int a;
   ...
   const(int)* pa = &a;

but this is not:

   int a;
   ...
   immutable(int)* pa = &a;


here, in former case we see `pa` as "alias to data".


so, what that quote essentially means is: "`const` pointers can 
point to mutable data, but `immutable` pointers cannot".

also, remember that slices are just "pointer, length" pairs, so 
when we are talking about "pointers" here, the same applies to 
slices too.


More information about the Digitalmars-d-learn mailing list