const by default.

Joseph M Link joelink at joelink.net
Tue Jul 4 07:14:35 PDT 2006



BCS wrote:
> Hasan Aljudy wrote:
>> Ahem.
>> Excuse me, I'm not very enlightened about this "const" issue, but if 
>> your suggestion implies that people like me who don't care about 
>> "const" will have to add "mutable" qualifiers all over the place, then 
>> I'm gonna have to side against this, with a big NO.
>>
>> If I've just said something that's too stupid, then please enlighten 
>> me. Thanks.
>>
> I'm not sure what is being suggested but it's something like this:
> 
> Given a function that takes a reference type as an argument. The stuff 
> the reference points to is not a valid target for a write unless you say 
> so.
> 
> 
> void fn1(char[] c)
> {
>     char i = c[5];    // allowed
>     c[4] = i;    // not allowed
> }
> 
> 
> void fn2(mutable char[] c)
> {
>     char i = c[5];    // allowed
>     c[4] = i;    // allowed
> }
> 
> 
> Furthermore, unless a variable is mutable, you can't pass it off to a 
> function in a mutable parameter
> 
> void fn3(char[] c)
> {
>     fn1(c);    // allowed
>     fn2(c);    // not allowed: c is immutable
> }
> 
> The issue as to the mutability of local variables is another thing all 
> together. I haven't heard any agreement on what is best here. One 
> thought I like is local reference type variables are localy mutable. 
> However if you are passing them to a function they become implicitly 
> immutable unless you say otherwise. (Assume that "@" is the grant 
> mutability operator)
> 
> void fn4()
> {
>     char[] c;
> 
>     c[5] = '\0';    // allowed
> 
>     fn1(c);        // allowed
>     fn2(c);        // not allowed: arg 1 is mutable;
>     fn2(@c)        // allowed
> }
> 
> In the general case I expect that this change will have little effect on 
> code. In my experience, most pass by reference cases are immutable 
> anyway. The rest should be easy to find and fix as long as DMD gives 
> good error messages.

I would also propose that mutable function parameters become locally 
mutable in the scope of the function.  This would make it necessary to 
always 'grant mutability' and those make it obvious when reading code.  ie:

void fn5(char[] b, mutable char[] d)
{
     char[] c;

     b[5] = '\0';   // not allowed: b is immutable
     c[5] = '\0';   // allowed
     d[5] = '\0';   // allowed

     fn1(b);        // allowed
     fn1(c);        // allowed
     fn1(d);        // allowed
     fn2(b);        // not allowed: arg 1 is mutable;
     fn2(c);        // not allowed: arg 1 is mutable;
     fn2(d);        // not allowed: arg 1 is mutable;
     fn2(@b)        // not allowed: b is immutable
     fn2(@c)        // allowed
     fn2(@d)        // allowed
}

Joe



More information about the Digitalmars-d mailing list