Reference variable from string

Hello all. I’m new to Arduino and C, and an coming from OOP methodology. I am hoping to use a string to reference a variable such as can be done in PHP:

$myVar1;
$myVar2 = "myVar1";
${$myVar2} = 5; // evals to $myVar1 = 5

Is anything like this possible? Is there any way to dynamically reference a variable? Thanks in advance all.

Is anything like this possible?

Not that exactly.

Is there any way to dynamically reference a variable?

Maybe. We'd need more details on what you are trying to accomplish.

string to reference a variable

Ummm...Are you talking about C++ reference variables?

Do you have a book or tutorial or something for C++? It's kind of hard to pick it up on your own without some kind of reference. (A little pun. Get it? A reference No? Oh, well...)

void setup()
{
    Serial.begin(9600);
}

String x("Hi!");
String & y = x; // This reference variable is an "alias" for x

void loop()
{
    Serial.print("1: x = ");Serial.println(x);
    Serial.print("1: y = ");Serial.println(y);

    y = "Goodbye for now!";

    Serial.print("2: x = ");Serial.println(x);
    Serial.print("2: y = ");Serial.println(y);
    Serial.println();

    x = "Hello again.";
    
    delay(1000);
}

Output


[color=#0000ff]1: x = Hi!
1: y = Hi!
2: x = Goodbye for now!
2: y = Goodbye for now!

1: x = Hello again.
1: y = Hello again.
2: x = Goodbye for now!
2: y = Goodbye for now!

.
.
.
[/color]

In C++ a reference variable is an alias for another variable. The reference is defined at the time the reference variable is declared. It can not be retargeted later.

Anyhow, for what it's worth, in the above sketch if you change the value of x it changes y. If you change y, it changes x. Whoop-de-do.

Some people have a hard time believing such things can be actually useful, but...

Regards,

Dave

Footnote: If you can stand a little more recursion, here's my favorite reference about references. It's about the Human Condition, not some geeky programming language:

"In the end, we are self-perceiving, self-inventing, locked-in mirages that are little miracles of self-reference."

— Douglas Hofstadter I Am a Strange Loop