const vs immutable for local variables

Jonathan M Davis jmdavisProg at gmx.com
Wed Nov 17 23:21:47 PST 2010


On Wednesday 17 November 2010 23:09:40 bearophile wrote:
> Jonathan M Davis:
> > 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.
> 
> In D2 for local variables that don't change use immutable when they are
> computed at run-time. I'd like to suggest you to use enum when they are
> known at compile-time, but in some cases this is bad (some examples of
> associative arrays, etc).

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?

> > 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?
> 
> Or is dmd dumb enough that it makes no optimization difference? :-)

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.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list