const as default for variables
Dejan Lekic via Digitalmars-d
digitalmars-d at puremagic.com
Tue Mar 17 06:55:34 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
> a) Introduce a new storage class, called 'var' or 'mut'.
> (Please, no bikeshedding on names at the moment. Let's stay on
> 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.
I definitely think this is a good idea. And if someone wants
mutable variable, we simply use proposed 'var' storage class.
More information about the Digitalmars-d