Obtaining an address given a (run time) variable name
Jonathan M Davis
newsgroup.d at jmdavisprog.com
Mon Jan 20 19:54:19 UTC 2025
On Monday, January 20, 2025 12:03:09 PM MST DLearner via Digitalmars-d-learn wrote:
> // In the code below, what fn needs to go in the commented-out
> line,
> // to make the program print 7, 11 rather than 7, 7?
>
> ```
> void main() {
>
> import std.stdio;
>
> int IntVar1 = 5;
> int IntVar2 = 7;
> int IntVar3 = 11;
>
> int* wkVarAddr;
> char[] wkVarName;
>
>
> wkVarAddr = &IntVar2;
> writeln("*wkVarAddr = ", *wkVarAddr);
>
> wkVarName = cast(char[])("IntVar3");
> // wkVarAddr = fn (wkVarName);
> writeln("*wkVarAddr = ", *wkVarAddr);
> }
> ```
>
Variable names are not a thing at runtime. They're entirely a compile time
thing, and the generated code does not know or care that there even were
names for variables in the source code. The compiled code is dealing with
registers, not actual variables with names. Debug information will have some
of that so that you can step through the source code in a debugger, but the
generated code itself doesn't do anything with variable names or provide any
way to access that information in your code. So, there's nowhere to look up
the value of a variable by name at runtime. If you want that, you're going
to have to store that information yourself somehow.
For instance, you could do something like a create an associative array with
the variable name as the key and the address as the value.
int*[string] addrs;
addrs["IntVar1"] = &IntVar1;
addrs["IntVar2"] = &IntVar2;
addrs["IntVar3"] = &IntVar3;
wkVarAddr = vars[wkVarName];
But the language isn't going to do anything like that for you automatically.
Also, there's really no reason to be doing anything with char[] instead of
string unless you're specifically planning on mutating the elements in your
string, and casting from a string literal to a char[] is almost never a good
idea, because it means that you could end up mutating the elements, which
would violate the type system guarantees - since immutable values are never
supposed to be mutated, and the compiler will potentially make the
assumption that an immutable value was not mutated (string is an alias for
immutable(char)[], and string literals are strings). If you _do_ need to
mutate the string for some reason, then use dup to get a mutable copy rather
than casting the literal, e.g.
char[] wkVarName = "IntVar3".dup;
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list