views:

132

answers:

3

When I create variable I just put the a name for it, but can I create the name of the variable like this:

int var+1= 1;

So basically that should be:

int var1=1;

I know I can't use the + sign to do that but is there way to do it?


EDIT

int g=1;
string hello+g = "sdljfsdl"; // So hello+g will be hello1

So it is like mixing variable value by another variable value to get new variable name.

+6  A: 

It is unlikely to be desirable, but you could use token pasting in the preprocessor:

#define PASTER(x, y) x ## y
#define EVALUATOR(x, y) PASTER(x, y)

int EVALUATOR(var, 1) = 1;
Jonathan Leffler
"unlikely to be desirable" is an understatement. Aren't there enough C Macros in the world?
Merlyn Morgan-Graham
@Merlyn: there are far too many macros - nevertheless, this one would more or less achieve the desired result, though the name is so long that it overwhelms the basic variable name. Which is another argument against using it.
Jonathan Leffler
@Johnathan: That's why you'd name it something short. And get rid of the *shift* because that's harder to type: `#define w(x, y) x ## y` ... `#define k(x, y) w(x, y)` ... `int k(var, 1) = 1;`. Or even better, name it after some function you never use, like realloc...
Merlyn Morgan-Graham
@Merlyn: you need the twin macro dance in general, so that given `#define M1 var` and `#define M2 1`, you can write `EVALUATOR(M1, M2)` and get the result `var1` rather than `M1M2`. As to length of name, then yes, you can shorten it. It doesn't make the idiom any better, but it can be shortened.
Jonathan Leffler
@Jonathan: Sorry, my deadpan is a little too deadpan today :) Cheers!
Merlyn Morgan-Graham
+13  A: 

You can do this with macros, but you really shouldn't need dynamic variable names. It sounds like this sort of problem can be solved with an array:

int vars[5];

vars[0] = 3;
vars[1] = 4; 
// etc.
Jacob
i can't use arrays
Ramiz Toma
@Ramiz: why can't you use arrays?
Jonathan Leffler
A: 

you almost certainly need std::map, or, if available, unordered_map. both will allow you to construct keys however you like and set/get values for those keys e.g.

std::map<string,int mymap;
string fixed = "fixed part";
string var = " 1"; //or construct this from a number
mymap[fixed+var] = 3; //fixed+var == "fixed part 1"
jk