const as default for variables
Walter Bright via Digitalmars-d
digitalmars-d at puremagic.com
Sat Mar 14 13:14:50 PDT 2015
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.
More information about the Digitalmars-d
mailing list