const vs immutable for local variables
spir
denis.spir at gmail.com
Thu Nov 18 11:30:34 PST 2010
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>
> wrote:
>
> > 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 it's
> > 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 more
> guarantees as a type modifier. I'd recommend immutable, because it's a
> specialization, and while the compiler can know that in a current function
> a const value is really immutable, it can't pass that knowledge to other
> functions.
>
> For example, a function may be overloaded on both const and immutable
> because the immutable one can make more assumptions. If you declare your
> variable const and call the function with your variable as the parameter,
> 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 be
> 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 data
> 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)?
Denis
-- -- -- -- -- -- --
vit esse estrany ☣
spir.wikidot.com
More information about the Digitalmars-d-learn
mailing list