const vs immutable for local variables

Jonathan M Davis jmdavisProg at gmx.com
Sat Nov 20 17:06:46 PST 2010


On Saturday 20 November 2010 10:47:27 Kagamin wrote:
> Jonathan M Davis Wrote:
> > > 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.
> 
> I see no difference. Both globals and locals can be initialized at runtime
> and both can be static.

I'm talking about direct initialization. If you do

immutable a = func();

in global scope, func() _must_ be callable at compile-time. If you do that at 
local scope, it will be done at runtime. If you declare a local variable as 
static, then it's in the same boat as a global variable because it _is_ a global 
variable as far as its lifetime goes, just not its scope. However, notice that 
both

auto a = func();
const a = func();

would have to have func() be callable at compile time if a is a global variable, 
whereas for a non-static local, it would be done at runtime. In comparison,

enum a = func();

_always_ must have func() be callable at compile-time. immutable says nothing 
about whether a variable's value must be known at compile time. And CTFE only 
kicks in when the compiler _must_ do the initialization at compile time.

Also, immutable by itself says nothing about static storage. It either has to be 
a global variable or be marked with static. And I believe that marking a global 
variable as static is redundant just like marking a method as public when it is 
already in a public block is redundant. static in C meant something for global 
variables, but C doesn't use modules.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list