'Renaming variables in C++
I want to know if a variable content can be used as variable name. Example below:
int a;
string b = "nombre";
I'm asking if "nombre" can replace "a" as variable name.
I'm trying to rename an object(like we rename files and folders).
Solution 1:[1]
If you want to be able to map strings to numeric values, you could create a map object:
#include <unordered_map>
#include <string>
#include <iostream>
int main()
{
std::unordered_map<std::string, int> vars {
{ "nombre", 5 },
{ "otro_nombre", 3 },
};
std::cout << vars["nombre"] << '+' << vars["otro_nombre"]
<< " = " << (vars["nombre"] + vars["otro_nombre"]);
}
This yields:
5+3 = 8
on the output stream. See it working on GodBolt.
Solution 2:[2]
You can use references to create an alias for an already existing variables, if this is what you're looking for.
int a = 5;
int& nombre = a; //nombre is now an alias for a
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | einpoklum |
Solution 2 | havel06 |