4

I was just curious to know if there is way to create a new variable with a new name every time a loop is executed.

For example:

#include <iostream>
int main()
{
    for (int x = 1 ; x<=5 ; x++)
       int a_x;
    return 0;
}

5 new variables should be created with names a_1, a_2, ..., a_5

The above code just shows what I am looking for and is not the answer.

Is this possible without using arrays?

12
  • are you aware of this fancy new thing called array? Commented Dec 10, 2014 at 12:18
  • 1
    Simply NO You cant!!! Commented Dec 10, 2014 at 12:18
  • 1
    What do you want to do with these variables? Do you want them to exist after the loop? In that case, declare an array outside the loop. If not, you'll need to explain why you think you want a different name for each iteration; that doesn't make much sense. Commented Dec 10, 2014 at 12:19
  • 1
    Sure... write a program to write your program. Commented Dec 10, 2014 at 12:21
  • 1
    @KarolyHorvath Thanks for the information :) New to this forum and will keep your advice in mind the next time. Commented Dec 10, 2014 at 12:35

3 Answers 3

5

No, there is no way to do what you've outlined (directly). Here are several possible alternatives:

  1. First off, if you do not need the "variables" to be accessible outside the loop, just use a normal local variable:

    for (int x = 1; x <= 5; ++x) {
      int a = whatever;  // This will be freshly redeclared & reinitialised in each iteration
    }
    
  2. If the bounds of the iteration are known at compile time, you can use an array:

    std::array<int, 5> a;
    for (int x = 0; x < a.size(); ++x) {
      a[x];
    }
    
  3. If the bounds are only known at runtime, use a dynamic array:

    std::vector<int> a(the_runtime_size);
    for (int x = 0; x < a.size(); ++x) {
      a[x];
    }
    
  4. If you really need individual variables for some reason (and you know the number at compile time), you could resort to preprocessor tricks with Boost.Preprocessor. But that is far above beginner level:

    #include <boost/preprocessor>
    
    #define DECLARE_MY_VARIABLE(z, idx, name) \
      int BOOST_PP_CAT(name, BOOST_PP_CAT(_, idx));
    
    BOOST_PP_REPEAT(5, DECLARE_MY_VARIABLE, a)
    

    The code above will expand to:

    int a_0; int a_1; int a_2; int a_3; int a_4;
    

    You could of course take this several steps further, to have each of the variables of a different type, or name them by names instead of by indices. It will just require more macro magic.

    Disclaimer: Do NOT use this approach unless you very clearly know you need it. Even then, reconsider twice before you actually do that. And if you still do, document it heavily. Stuff like this should generally be hidden deep inside a library under a nice & clean user-friendly interface.

Sign up to request clarification or add additional context in comments.

6 Comments

Plus one; particularly for the evil genius of (4). You could do this with templates too, albeit with a slightly different notation.
for exactly the same reason I feel an urge to downvote. you're giving an infant the nuclear launch codes...
@KarolyHorvath There is a disclaimer. And if someone has "a will to learn," they'll understand some stuff is not to be learned immediately. And if someone arrives at this via a search, they may be more of a major general than an infant.
@Angew Point 4 is what I was looking for ,yup but it is far above beginner level xD. Very Informative answer :)
@KarolyHorvath I've actually added an explicit disclaimer, just in case.
|
3

No you can't do that in C++.

The best thing to do in this case would be to create an array of ints and use the for loop to populate them.

int a_x[5];
for (int x = 1 ; x<=5 ; x++)
       a_x[x - 1] = /*ToDo - something*/

Note that

  1. arrays are zero-based: can you see how I've used x - 1. The normal thing to do would be to rebase x in the for loop though: for (int x = 0 ; x < 5; ...

  2. arrays are not initialised. You must populate the contents.

5 Comments

FFS, start the loop from 0.
Indeed, most people would do that (unless they are diehard FORTRAN programmers).
@Bathsheba No way out without using arrays?
Not easily no. C++ doesn't allow you to declare new variables at run-time. You could build your own symbol table though; e.g. a std::map of variable names and values.
You can use collections but if you know the size of variables you need, an array is the best choice.
1

While many will assume that this is impossible, it can be achieved with the preprocessor. It is necessary that the loop count is known at compile time. Here I use the Boost Preprocessor Library. The example for PP_REPEAT does almost exactly what you want.

#include <boost/preprocessor/repetition/repeat.hpp>

#define DECL(z, n, text) text ## n = n;

int main()
{
  BOOST_PP_REPEAT(5, DECL, int a_) // expands to int a_0 = 0; int a_1 = 1; ...
  return 0;
}

Please remember: this is certainly not what you want. You probably want to use an array. Do only use this if you are absolutely certain that you need it.

2 Comments

@pmr'Please remember: this is certainly not what you want. You probably want to use an array. Do only use this if you are absolutely certain that you need it.' In what way is it bad?
@Mohit_Bhasi The technique is obscure. It took people years to even discover that this is possible with the pre-processor. The language works perfectly fine without this feature. There are rare cases where this is necessary. Yours certainly isn't one of them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.