Jump to content

Dynamic variable names: Difference between revisions

New post.
imported>Arakov
(New post.)
Line 167:
<pre>
Hello world!
</pre>
 
=={{header|C++}}==
C++ is a compiled language which means that it loses information about names in code in the compilation process of translation to machine code. This means you can't use any information from your code at runtime without manually storing it somewhere. We therefore simulate dynamic variables using an unordered_map.
<syntaxhighlight lang="c++">
#include <algorithm>
#include <cstdint>
#include <iostream>
#include <string>
#include <unordered_map>
 
int main() {
std::unordered_map<std::string, int32_t> variables;
 
std::string name;
std::cout << "Enter your variable name: " << std::endl;
std::cin >> name;
 
int32_t value;
std::cout << "Enter your variable value: " << std::endl;
std::cin >> value;
 
variables[name] = value;
 
std::cout << "You have created a variable '" << name << "' with a value of " << value << ":" << std::endl;
 
std::for_each(variables.begin(), variables.end(),
[](std::pair<std::string, int32_t> pair) {
std::cout << pair.first << " = " << pair.second << std::endl;
}
);
}
</syntaxhighlight>
{{ out }}
<pre>
Enter your variable name:
foo
Enter your variable value:
42
You have created a variable 'foo' with a value of 42:
foo = 42
</pre>
 
908

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.