C ++ string value as another string name

How to convert vartiables int ints value in C ++? as in this php snippet.

$string = 'testVar';

${$string} = 'test';

echo $testVar; // test

      

0


a source to share


5 answers


How about using the card?



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

      

+6


a source


I don't know PHP, but I don't think you can do this 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.



This is similar to what you can only do in a scripting language where the source code is in memory, or at least some representation of a syntax tree.

+3


a source


This is not something you can do in C ++. When you compile C ++ code, information about which name functions and variables are lost (technically, they can be stored in symbol tables, but they are for debugging purposes only). To accomplish something like this, you would need to use a map or some other similar data structure that looks more like a PHP array.

+1


a source


It looks like you can use pointers:

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

      

After compilation, the C ++ compiler discards information similar to the original variable names, so you need to use lower-level constructs to do the same types.

+1


a source


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

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

      

0


a source







All Articles