const vs immutable for local variables

Jonathan M Davis jmdavisProg at
Thu Nov 18 11:57:40 PST 2010

On Thursday, November 18, 2010 11:37:51 Kagamin wrote:
> Jonathan M Davis 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.
> > 
> > So, the question is: what are the advantages of one over the other?
> > Specifically, my concern is how likely compiler optimizations are. Does
> > using immutable make compiler optimizations more likely? Or would const
> > do just as well if not better? Or is dmd smart enough that it really
> > doesn't matter if you use const or immutable on local variables which
> > never change?
> > 
> > - Jonathan M Davis
> Doesn't immutability imply static storage? I also thought, it's a way to
> force CTFE.

No. If it did, you couldn't initialize immutable stuff at runtime. Apparently, in 
the case of globals or member variables (which have to be initialized statically 
anyway), it does mean that they could be optimized out (e.g. there's an open bug 
report on the fact that immutable fields in structs don't take any space), but 
that's no the case for local variables which can be initialized at runtime. An 
enum, on the other hand, _must_ be known at compile-time, and it's not going to 
take any storage (except for what it puts on the heap if it's a reference type), 
so enums are the way to declare compile-time constants in D.

- Jonathan M Davis

More information about the Digitalmars-d-learn mailing list