0

How can i convert a vartiables value int anothers name in C++? like in this php snippet.

$string = 'testVar';

${$string} = 'test';

echo $testVar; // test
1
  • 1
    Why do you want to do that? Maybe there's another way, without converting a vartiable's value into another's name. Commented May 17, 2009 at 2:23

5 Answers 5

6

How about using a map?

#include <iostream>
#include <map>
#include <string>

using namespace std;

map<string, string> hitters;

hitters["leadoff"] = "Jeter";
hitters["second"] = "Damon";
hitters["third"] = "Teixiera";
hitters["cleanup"] = "Matsui";

string hitter = "cleanup";

cout << hitters[hitter] << endl;
Sign up to request clarification or add additional context in comments.

Comments

3

I don't know PHP, but I don't think you can do that in C++. A variable name has no runtime representation in a compiled C++ program, so there is no way to load its name at runtime like that.

This seems to be something you can only do in a scripting language where the original source code is in memory or at least some representation of the syntax tree.

1 Comment

...or by implementing an interpreter or introspection layer.
1

This isn't something you can do in C++. When you compile C++ code, the information about what names functions and variables are is lost (technically, it can be stored in symbol tables, but those are only for debugging purposes). To accomplish anything like this, you'd need to use a map or other similar data structure, which is rather like a PHP array.

Comments

1

It sounds like you may want to use pointers:

string testVar;
string *str = &testVar;
*str = "test";
cout << testVar << endl; // test

After compiling, the C++ compiler discards information like the original names of variables, so you have to use lower level constructs to do the same kinds of things.

Comments

0

If you compile your program with a symbol table, you can use "readelf -s yourexecutable" (linux) to get the symbol table. Then grep on the output with the variable name and from the output get the address by using the"cut" command.

readelf -s a.out | grep ' var$' | tr -s ' '| cut -d' ' -f3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.