Block statements and memory management

Johan Engelen j at j.nl
Sat Mar 16 15:53:26 UTC 2019


On Saturday, 16 March 2019 at 03:47:43 UTC, Murilo wrote:
> Does anyone know if when I create a variable inside a scope as 
> in
> {int a = 10;}
> it disappears complete from the memory when the scope finishes? 
> Or does it remain in some part of the memory? I am thinking of 
> using scopes to make optimized programs that consume less 
> memory.

Others have made good points in this thread, but what is missing 
is that indeed scopes _can_ be used beneficially to reduce memory 
footprint.

I recommend playing with this code on d.godbolt.org:
```
void func(ref int[10] a); // important detail: pointer

void foo()
{
     {
         int[10] a;
         func(a);
     } {
         int[10] b;
         func(b);
     }
}
```

Because the variable is passed by reference (pointer), the 
optimizer cannot merge the storage space of `a` and `b` _unless_ 
scope information is taken into account. Without taking scope 
into account, the first `func` call could store the pointer to 
`a` somewhere for later use in the second `func` call for 
example. However, because of scope, using `a` after its scope has 
ended is UB, and thus variables `a` and `b` can be used.

GDC uses scope information for variable lifetime optimization, 
but LDC and DMD both do not.
For anyone interested in working on compilers: adding variable 
scope lifetime to LDC (not impossibly hard) would be a nice 
project and be very valuable.

-Johan





More information about the Digitalmars-d-learn mailing list