Indirect access to variables.

user1234 user1234 at 12.de
Fri Dec 29 21:25:44 UTC 2023


On Friday, 29 December 2023 at 17:11:49 UTC, DLearner wrote:
> Compile-time:
> [...]
> Is there a 'foo1' that yields 1 from the snippet below?
> [...]
> Similarly, execution-time, is there a foo2 that wields 2 from 
> the snippet below:
> [...]

**compile-tome**

```d
void main() {

     import std.stdio;

     size_t var1 = 1;
     size_t var2 = 8;

     writeln(mixin(var1.stringof));
     writeln(mixin(var2.stringof));
}
```

**run-tome**

Given the information you provide I'd say you can use an 
associative array:

```d
size_t*[string] registry;

void main() {

     import std.stdio;

     size_t var1 = 1;
     size_t var2 = 8;

     registry[var1.stringof] = &var1;
     registry[var2.stringof] = &var2;

     writeln(*registry[var1.stringof]);
     writeln(*registry[var2.stringof]);
}
```

but take care to the entries lifetime, that's basically not safe 
as this escapes stack addresses.


More information about the Digitalmars-d-learn mailing list