Is it possible to initialize variable with same name but different numbers at the end?

Viewed 267

In a situation I have to define some variables where I have control on parts of the variable names (like var below).

float var1, var2, var3....;

But I do not have any control on the numbers that they will take. (This is because these var* I am producing from some other code where everytime I compile, these numbers at the end will be different).

My question: Is there any way to define these variables a priori?

Like (lets say that the var* are generated within var100.)

float var1,...,var100;

without explicitly typing each and every var*. It would have been much better to have array in this position, but is there any way to do this in this way?

1 Answers

If you do know the bounds and you do not mind leaving unused variables, you can play with the preprocessor to generate them. For instance:

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

#define ONE_FLOAT(z, n, x) float var##n;

BOOST_PP_REPEAT(100, ONE_FLOAT, x)

Note 1: implementing BOOST_PP_REPEAT by hand is out of the scope of this answer.

Note 2: of course, arrays and similar solutions are the proper ones, but the question disallows those.


Edit: this was written before knowing that the bounds where known ahead of time.

No. You are asking how to define variables without knowing their name, which is impossible.

It does not make sense either, because if you don't know their names, you cannot do anything with them either. It is like trying to write equations with symbols without knowing what the symbols are.

You will need some kind of code generation script that will fill them in for you and then possibly #include them in the right place. Same for the places you actually use the variables.

Related