Convert string to variable name or variable type

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.

Leave a Comment