const as default for variables

weaselcat via Digitalmars-d digitalmars-d at puremagic.com
Sat Mar 14 17:17:17 PDT 2015


On Sunday, 15 March 2015 at 00:03:37 UTC, Orvid King wrote:
> On Saturday, 14 March 2015 at 20:15:30 UTC, Walter Bright wrote:
>> I've often thought, as do many others here, that immutability 
>> should be the default for variables.
>>
>> [This is a long term issue. Just thought maybe it's time for a 
>> conversation about it.]
>>
>> Because immutable is transitive, declaring variables as 
>> immutable by default would be problematic. A more practical 
>> way would be to make them const.
>>
>> As it is now:
>>
>> 1.    int x = 1;       // mutable
>> 2.    auto x = 1;      // mutable
>> 3.    const x = 1;     // const
>> 4.    immutable x = 1; // immutable
>>
>> Case (1) is what I'm talking about here. If it is made const, 
>> then there are a couple ways forward in declaring a mutable 
>> variable:
>>
>> a) Introduce a new storage class, called 'var' or 'mut'. 
>> (Please, no bikeshedding on names at the moment. Let's stay on 
>> topic.)
>>
>> b) Use 'auto' as meaning 'mutable' if the initializer is also 
>> mutable. Extend 'auto' to allow an optional type,
>>
>>    auto T t = initializer;
>>
>> There may be some ambiguity issues with 'auto ref', haven't 
>> thought it through.
>>
>>
>> Once there is a non-default way to declare variables as 
>> mutable, a compiler switch can be added to change the default 
>> to be const. Eventually, the language can default to them 
>> being const, with a legacy switch to support the mutable 
>> default.
>
> Why would this be even slightly useful? If a value is constant, 
> it _should not_ be a variable.

C heritage.


More information about the Digitalmars-d mailing list