-1
std::string VariableName = "name";
int (VariableNameHere) = 5;

From my understanding of c++ what I am asking is most likely impossible. If it is please post possible alternative solutions. Thanks!

4
  • 1
    It's possible with macros but the name still must be known at compile time. Commented Jan 8, 2018 at 22:34
  • 5
    You could use a std::unordered_map<string, int> and then do mymap[VariableName] = 5; Commented Jan 8, 2018 at 22:36
  • 2
    Alternatively #define VariableName name and then int VariableName = 5;, which relies on the preprocessor. But, since I abhor the preprocessor, please don't do that. Commented Jan 8, 2018 at 22:45
  • Solutions to what? What are you actually trying to accomplish with this approach? Why do you need a variable whose name is defined in another variable? Commented Jan 9, 2018 at 0:04

1 Answer 1

4

As you have it is not possible, you would need to have some kind of look-up system, such as:

std::map<std::string, int> variables;
...
variables["name"] = 5;
Sign up to request clarification or add additional context in comments.

1 Comment

Using regular data structures rather than variables with special, magical names is always better.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.