const vs immutable for local variables

Jonathan M Davis jmdavisProg at gmx.com
Thu Nov 18 01:27:27 PST 2010


On Thursday 18 November 2010 00:50:58 Russel Winder wrote:
> On Wed, 2010-11-17 at 23:21 -0800, Jonathan M Davis wrote:
> [ . . . ]
> 
> > Well. yes. enums are definitely tha case for compile time constants. The
> > question is for runtime. And why would you suggest immutable over const
> > for runtime?
> 
> Why use enums rather than immutable for values that are known at compile
> time?

enums _must_ known at compile time. immutable variables don't, so they won't 
actually be compile time constants. If you use immutable, it'll be created at 
runtime and be less efficient.

> immutable is really immutable whereas const implies that there is the
> possibility of change -- at least that is how I read the documentation
> and TDPL.

Sure. You can change const if there are other references to the data which are 
mutable, but if there aren't then it makes no difference. And when dealing with 
value types, there really shouldn't be much - if any - difference between const 
and immutable, because you can't change them in either case.

The real question here is whether there's any real difference in how well 
unnecessary local variables get optimized out when they're const or immutable. 
Do they disappear more as const? or as immutable? Or is it the same for both?

> > I really don't see any reason why const vs immutable would make any
> > difference for a local variable except insofar as a function takes an
> > immutable argument rather than a const one. I would think that both
> > would be optimized identically, but I don't know.
> 
> I am a fan of single assignment so I put immutable on all my variables
> except for loop control variables and accumulators.  I haven't yet seen
> a need for const.
> 
> Interesting, and possibly not irrelevant, side note:  In a moment of
> complete stupidity I spelled immutable as invariant so had code like:
> 
> 	invariant n = 1000000000 ;
> 	invariant delta = 1.0 / n ;
> 
> instead of:
> 
> 	immutable n = 1000000000 ;
> 	immutable delta = 1.0 / n ;
> 
> and it all worked just fine.  I have no idea how or why, but it did!

It used to be that immutable wasn't a keyword. invariant was used. Some folks 
complained and Walter added immutable. So, immutable is supposed to be used for 
variables whereas invariant is just for invariants, but it still works to use 
invariant instead of immutable.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list