head const (again), but for free?

Q. Schroll qs.il.paperinik at gmail.com
Wed Jan 13 22:15:59 UTC 2021


On Wednesday, 13 January 2021 at 20:21:33 UTC, jmh530 wrote:
> On Wednesday, 13 January 2021 at 19:42:14 UTC, Meta wrote:
>> [snip]
>>
>> Is there even any value to having head-const in a language? As 
>> I think Walter has said before, it's basically just 
>> documentation/convention in C++. I can see the value in 
>> head-immutable, in terms of type system guarantees, but not 
>> head-const.
>
> I don't really understand the difference between head-const and 
> head-immutable.

Do you understand the difference between const and immutable (the 
transitive ones)?
For declaring an int, it's almost the same.

const int i = 0;
immutable int j = 0;

You cannot write i and j regardless which one you use. Only &i 
and &j will be typed differently, and that's where the difference 
begins.

int i = 0;
const(int)* p = &i; // okay
immutable(int)* q = &i; // error

But because there are no indirections in an int, for p and q it 
would be the same if const and immutable weren't transitive. 
Enter double pointers:

int i = 0;
int* p = &i;
immutable(int*)* qq = &p; // error, **qq could change through i 
and *p.
const(int*)* pp = &p; // okay, const only means no write through 
this

Here, it makes a difference that const and immutable are 
transitive.

int i = 0;
head_immutable(int*) p = &i; // okay, immutable ptr to mutable 
value
head_const(int*)* pp = &p; // okay, too
int* q = &i;
head_immutable(int*)* qq = &p; // error, *qq could change through 
q.

Head immutable is more restrictive than head const, obviously.


More information about the Digitalmars-d mailing list