Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to variable name or variable type

Tags:

c++

string

Is it possible to convert strings into variables(and vise versa) by doing something like:

makeVariable("int", "count");

or

string fruit;
cin >> fruit;    // user inputs "apple"
makeVariable(fruit, "a green round object");

and then be able to just access it by doing something like:

cout << apple; //a green round object

Thanks in advance!

like image 649
Rhexis Avatar asked Aug 22 '11 04:08

Rhexis


1 Answers

No, this is not possible. This sort of functionality is common in scripting languages like Ruby and Python, but C++ works very differently from those. In C++ we try to do as much of the program's work as we can at compile time. Sometimes we can do things at runtime, and even then good C++ programmers will find a way to do the work as early as compile time.

If you know you're going to create a variable then create it right away:

int count;

What you might not know ahead of time is the variable's value, so you can defer that for runtime:

std::cin >> count;

If you know you're going to need a collection of variables but not precisely how many of them then create a map or a vector:

std::vector<int> counts;

Remember that the name of a variable is nothing but a name — a way for you to refer to the variable later. In C++ it is not possible nor useful to postpone assigning the name of the variable at runtime. All that would do is make your code more complicated and your program slower.

like image 120
wilhelmtell Avatar answered Sep 23 '22 01:09

wilhelmtell