const as default for variables

Xinok via Digitalmars-d digitalmars-d at
Sat Mar 14 15:06:43 PDT 2015

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.

My two and a half cents, I think this is going to lead to all 
sorts of complications and simply wouldn't be worth the hassle. 
While I believe that immutable by default is a fine choice for 
any new language, D was designed with "mutable by default" in 
mind and it's simply too late to try and change that now.

For example, this could be an issue for generic functions:

     void foo(T)(T[] arr){
         T value = arr[0]; // Mutable or immutable?

Also, you forgot a fifth case where only part of the type is 

5. const(T)[] x = ...

More information about the Digitalmars-d mailing list