I need a way to concurrently create variables with a loop.

Like... Instead of

int my_var_1 = 1;
int my_var_2 = 1;
int my_var_3 = 1;

Because the user may need thousands of variables, and I don't want there to be a limit. So I was wondering if there was a way to declare variables with a loop appending a number to the end of the name.

Something like the following:

for(int i=1; i<3; i++) {
int my_var_ + i = 1;
}

This in theory would create three integers named my_var_1, my_var_2, and my_var_3, and set the value of them all to 1.

Can I do something like this?

Recommended Answers

All 4 Replies

Can't u use an array?

#include <iostream>
using namespace std;
main()
{
short variable_number;
cin >> variable_number;
int *my_var = new int[variable_number];
for(int i = 0; i< variable_number; i++)
{
my_var[i] = 1;
}
return 0;
}

Ah, okay.. Thanks.

Can't u use an array?

#include <iostream>
using namespace std;
main()
{
short variable_number;
cin >> variable_number;
int *my_var = new int[variable_number];
for(int i = 0; i< variable_number; i++)
{
my_var[i] = 1;
}
return 0;
}

To be a little pedantic, that code has the potential to leak memory, so you should be careful. Every new should have a delete to go with it, so the snippet should be:

#include <iostream>

int main()
{
   short variable_number;
   std::cin >> variable_number;

   int *my_var = new int[variable_number];
   for(int i = 0; i< variable_number; i++)
      my_var[i] = 1;

   // Do things with the array
   
   delete[] my_var;   // Free the memory that we used for the array when it's no longer needed
   
   return 0;
}

Even better, use std::vector instead:

#include <iostream>
#include <vector>

int main()
{
   short variable_number;
   std::cin >> variable_number;

   std::vector< int > my_var(variable_number);
   for(int i = 0; i< variable_number; i++)
      my_var[i] = 1;
   
   return 0;
}

This way, the memory management is taken care of for you.

There are people who say that you should learn to use arrays properly before you start with std::vector , and they've probably got a point, but at the end of the day the slight overhead is better than a bunch of memory leaks :o)

Haha, I forgot the delete[]
Nvm, thx for the correction.(I had a long day trying to solve my problem and I write it while reading another website)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.