const vs immutable for local variables

Steven Schveighoffer schveiguy at yahoo.com
Thu Nov 18 04:50:51 PST 2010


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.

-Steve


More information about the Digitalmars-d-learn mailing list