2

I want to be able to input the name of an already existing variable and then use that variable in a function. Is there a way to do this?

For example my code could look something like this:

int a = 1;
int b = 2;

char variableName;
std::cin >> variableName;

Is there a way I could then input "a" as variableName and then use the variable a in a function.

2
  • 6
    Variable names are normally gone completely after compilation. Commented Feb 3, 2018 at 15:38
  • 1
    That's simply not how C++ works. Commented Feb 3, 2018 at 15:47

3 Answers 3

4

As a compiled language, C++ does not support runtime access to variable names - basically, after compiling, the names of variables are gone, and the resulting executable does not know about them anymore.
So there is no way you can access them runtime.

Sign up to request clarification or add additional context in comments.

Comments

1

No this is not possible. What you can do is you can use pointers. Pointers are best used for dynamic objects creation and passing into the functions.

Further information about pointers can be studied here

Comments

1

No, there is no concrete way to do this, since C++ does not support runtime access to these names, but you can achieve similar behavior using a std::unordered_map, as follows:

std::unordered_map<std::string, int> variables;
variables["a"] = 1;
variables["b"] = 2;

std::string variableName;
std::cin >> variableName;

// Check to see if 'variableName' exists in the map, and then
// access it by index for whatever you want.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.