Sequential Variables

I want to automate the creation and editing of a series of sequential variables within a piece of code, but I'm still fresh to C++, so I'm a little shaky on the doing part.

What I'm looking for is a way to have a pre-defined variable suffix, i.e. "var" and be able to append numbers onto it, automatically i.e. "000" - "999" to create a series of variable labels; without having to type in every single one manually, or having 1000+ lines of code just to declare those variables.

~Mobius

I'm guessing you haven't learned about arrays yet - if not check out the tutorial on this site about them: http://www.cplusplus.com/doc/tutorial/arrays.html
I know about arrays, I was just seeing if there was another way about it. I guess I'm trying to unnecessarily overcomplicate the matter though, now that I reconsider it.

Thank you!
You can't create variable names runtime, they all have to be hard coded into the source code before compilation.

The closest you can get to what you want is either an array as previously suggested, or a container such as std::vector.
thats not right... YOU CAN!... per preprocessor... create a macro like:...

#define XI(num) int x##num

## is the token concatenation operator... but only usable in preprocessor directives...

calling the macro like:

1
2
3
4
for(int i = 0; i < number_of_vars_u_need;i++) 
{
XI(i) = 0;
}


there u got it...^^
Last edited on
You can't be serious? There is no way to use that. The only reason it would ever compile is if the compiler was smart enough to remove dead code (many are).

The C preprocessor is not capable of replicating names like that. You'd have to use something smarter, like m4.

And even then, the only place in the code where you know for sure that the variable exists is where you define it!
Also, you ought to note that the preprocessor does it's work before runtime, so it will not be running through the for loop checking values of i. Assuming I understand the preprocessor correctly, it will just scroll down through the code once and give you a loop like:

1
2
3
for(int i = 0; i < number_of_vars_u_need;i++) {
    int xi = 0;
}
I don't really see the point of all this. What with there being arrays and all...
Also, defining the variables inside the block limits their scope to within the block. And the preprocessor doesn't have the value of 'i' at compile time. You'd just be allocating and deallocating a variable named 'xi' 'number_of_vars_u_need' times.

Edit: Damn. I was beaten to it.
Last edited on
@zhuge : y... forgot that... damn^^...

@helios: i first defined the macro... as soon as u call it (the right way with an hard number) XI(1), for example, will resolve to :

int x1 = 0
Topic archived. No new replies allowed.