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.

Jani
  • 21
  • 2

3 Answers3

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.

Aganju
  • 6,295
  • 1
  • 12
  • 23
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

Muhammad Asad
  • 296
  • 2
  • 12
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.
Arnav Borborah
  • 11,357
  • 8
  • 43
  • 88