Reputation: 4309
I want to generate some variables using for command. look at code below:
for (char ch='a'; ch<='z'; ch++)
int ch=0;
It just an example, after running code above, I want to have int a, int b, int c ...
another example:
for (int i=0; i<10; i++)
int NewiEnd=0;
For example after running code above, we will have int New1End, int New2End etc.
Hope I'm clear enough, How can I do such thing in C++??
Upvotes: 1
Views: 314
Reputation: 33637
In C/C++ the variable names have "gone away" by the time the code has been compiled and run. You can't print out the name of an existing variable at run time via "reflection"...much less make new named variables. People looking for this feature find out that the only generalized way you can do it falls down to using the preprocessor:
generic way to print out variable name in c++
The preprocessor could theoretically be applied to your problem as well, with certain constraints:
Writing a while loop in the C preprocessor
But anyone reading your code would probably drive a stake through your heart, and be justified in doing so. Both Sunday-morning laziness and a strong belief that it's not what you (should) want leads me to not try and write a working example. :-)
(For the curious, the preprocessor is not Turing-Complete, although there are some "interesting" experiments)
The nature of C/C++ is to have you build up named tables on an as-needed basis. The languages that offer this feature by default make you pay for the runtime tracking of names whether you wind up using reflection or not, and that's not in the spirit of this particular compiled language. Others have given you answers that are more on the right track.
Upvotes: 2
Reputation: 9555
What you seem to want is a map of the type:
std::map<std::string, int> ints;
This will let you call "variables" by name:
ints["a"] = 0;
ints["myVariable"] = 10;
Or as given in your example:
std::map<char, int> ints;
for (char ch='a'; ch<='z'; ch++)
ints[ch] = 0;
If you are just about to use 'a' - 'z' you could use an array of ints:
int ints['z' + 1];
ints['a'] = 0;
ints['z'] = 0;
But this allocates unnecessary space for the ascii characters below 'a'.
Upvotes: 4
Reputation: 103751
No, not possible, not exactly. However, this is possible:
std::map<char,int> vars;
for (char ch='a'; ch<='z'; ch++)
vars[ch] = 0;
std::cout << vars['a'] << vars['b'] << vars['c'];
You can also have std::map<std::string, int>
.
std::map<std::string,int> vars;
for (int i=0; i<10; i++)
vars["New" + std::to_string(i) + "End"] = 0;
std::cout << vars["New5End"];
Upvotes: 7