tags:

views:

147

answers:

4

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

$string = 'testVar';

${$string} = 'test';

echo $testVar; // test
+3  A: 

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.

Uri
...or by implementing an interpreter or introspection layer.
dmckee
+1  A: 

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.

Paul Fisher
+1  A: 

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.

Greg Hewgill
+5  A: 

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;
Bklyn