Take the 2-minute tour ×

for example lets say your pulling data from somewhere and you put it in a string variable then you want to use the data inside of it to be the another strings name:

int main(void){

   string strVar ="StringData"; //this is a string variable with text inside 

   cout<<strVar<<endl;    //displaying the variables contents

   string strVar.c_str() = "stuff in string variable 'StringData'"; //this uses what was inside of strVar to be the name of the new string variable

   cout<<StringData<<endl; //prints the contents of the variable StringData (who got its name from the data inside of strVar

stuff in string variable 'StringData'

i know you definitely cannot do it in this manner and in this example your would have to know before hand what was in strVar before you used the variable StringData, but can we theoretically do this?


Thanks everyone, so what i get from you all is basically its not possible, C++ is not a Dynamic variable language and the closest thing i can get to it is with a map (string, string)

share|improve this question
Probably map<string, string> is what you want? –  nhahtdh Jun 25 '12 at 4:12
The short answer: no, it's not possible. –  Marlon Jun 25 '12 at 4:15

4 Answers 4

up vote 2 down vote accepted

Nothing explicitly like you are thinking, but maybe you'd be interested in a std::map? Sounds like what you want is a Key-Value pairing.

Reference for std::Map -> http://www.cplusplus.com/reference/stl/map/


#include <map>
#include <string>
#include <iostream>
using namespace std;

int main(void)
    map<string, string> myMap;
    myMap.insert(pair<string, string>("StringData", "Stuff in StringData"));

    // Get our data
    cout << myMap["StringData"] << endl;

    return 0;
share|improve this answer
thanks, ill give it a try and see if it solves my problem –  Tech Jun 25 '12 at 6:46

Variable names exist only at compile time in C++. The closest you can come is to use a map with string keys.

share|improve this answer
well then, ill have to seriously rethink my approach to this program then, thanks for the help @Antimony –  Tech Jun 25 '12 at 4:21

I'm not sure what you're asking, but if you want to have "dynamic" variable names, then you can't do that in the code directly. You would have to use some map-type data construct. Look at std::hash_set or std::map if you can use the standard library.

share|improve this answer

There are languages where you can create variables dynamically. C++ isn't one of them ;)

share|improve this answer

Your Answer


