const vs immutable for local variables
schveiguy at yahoo.com
Thu Nov 18 11:43:57 PST 2010
On Thu, 18 Nov 2010 14:30:34 -0500, spir <denis.spir at gmail.com> wrote:
> On Thu, 18 Nov 2010 07:50:51 -0500
> "Steven Schveighoffer" <schveiguy at yahoo.com> wrote:
>> On Wed, 17 Nov 2010 23:41:33 -0500, Jonathan M Davis
>> <jmdavisProg at gmx.com>
>> > In C++, I tend to declare all local variables const when I know that
>> > they aren't
>> > going to need to be altered. I'd like to something similar in D.
>> > However, D has
>> > both const and immutable. I can see clear differences in how const and
>> > immutable
>> > work with regards to function parameters and member variables, but
>> > not as
>> > clear with regards to const and immutable.
>> immutable and const storage classes are identical as far as the compiler
>> is concerned (neither can ever be changed). However, immutable gives
>> guarantees as a type modifier. I'd recommend immutable, because it's a
>> specialization, and while the compiler can know that in a current
>> a const value is really immutable, it can't pass that knowledge to other
>> For example, a function may be overloaded on both const and immutable
>> because the immutable one can make more assumptions. If you declare
>> variable const and call the function with your variable as the
>> then it calls the const version, even though the data is really
>> immutable. You lose out on some possible optimizations.
>> Also, pure functions that take immutable can be 'strongly pure' so can
>> better optimized.
>> All this is moot of course if your variable is a value type :) But I'd
>> still recommend immutable even in those cases because the definition is
>> clearer -- immutable data can never change, it is assumed that const
>> can change, but in your case, it will never change. If nothing else, it
>> conveys the most accurate information to the reader of the code.
> Does all the thread finally mean that const is relative to variables,
> while immutable is (as in FP) relative to elements (be them values or
> referenced thingies)?
const applied to a value type means the same thing as immutable. For
const int i;
immutable int i;
both say the same thing -- i will never change.
const applied to a *reference* type means that you cannot change that data
*through that reference*, but it may change through another reference.
const int *j = &i;
I can change i, but not through j.
immutable applied to a reference type means that *nobody* can change that
data through any reference. It is safe to assume it never changes.
immutable int j;
immutable int *ip = &i; // Error!
immutable int *jp = &j; // OK
So while immutable and const are basically equivalent on value types (as
was the original question), it's more 'correct' IMO to declare them as
immutable because of the meaning of immutable -- this will never change,
no matter what.
More information about the Digitalmars-d-learn