fedemengo
fedemengo

Reputation: 696

Is it possible to use dynamic name for variables in c++

I'd like to use dynamic names if it is possible. Here an example about what I mean:

int sol1,sol2;
for(int i=1; i<3; i++){
   sol"i"=i*i;
   return max(sol1,sol2);
}

With sol"i" I mean sol1 in the first cycle (when i=1) and sol2 for the second (when i=2). Is this possibile in a similar way?

Upvotes: 11

Views: 24347

Answers (5)

Ophir Gvirtzer
Ophir Gvirtzer

Reputation: 622

As said by others, what you're asking about is impossible, but there are many alternative solutions. Using a C-array or an std::array of ints as suggested is the best approach if you can use it.

But supposed the variable names cannot be changes (for example, they are argument of a function, and you don't want to change the signature), but you still want to address them by index, so you can loop through them. One approach is to use an array of pointers

int * sol[2] ={&sol0,&sol1};
*sol[0]=1;

This works, but it's quite ugly in my opinion. Another solution is to use a tuple:

std::tuple<int&,int&> sol=std::tie(sol0,sol1);
std::get<0>(sol)=1;

Yet another option is to copy your values into an array, process the array, and copy them back.

Upvotes: 1

Andrew
Andrew

Reputation: 5352

It is not possible to do what you're asking, but there are alternatives that you should find equally expressive.

Probably the most common approach is to use a vector (or array) and index it:

std::vector<int> sol(2);
for (int i = 0; i < 2; ++i) {
    sol[i] = i * i;
}

Another approach is to use a std::map to map the desired name to the resulting variable:

std::map<std::string, int> variables;
for (int i = 1; i < 3; ++i) {
    std::string varname = "sol" + std::to_string(i);
    variables[varname] = i * i;
}

Note, however, that this is an extremely slow solution. I mention it only because it allows you to do something similar to your original example. Use the vector / array approach instead.

Upvotes: 14

Mr.Yellow
Mr.Yellow

Reputation: 198

Wouldn't a simple int array, solve your problem?!?

int sol[2];
for(int i=0; i<2; i++){
  sol[i]=(i+1)*(i+1);
  return max(sol[0],sol[1]);
}

Upvotes: 0

Marcin Hoppe
Marcin Hoppe

Reputation: 541

This is not possible. You can use an array instead:

int sol[2];
for(int i=0; i<2; i++){
  sol[i]=i*i;
}
return max(sol[0],sol[1]);

Please note that in C++ arrays are 0-indexed.

Upvotes: 3

rgoble
rgoble

Reputation: 329

You are better off using an array.

int sol[2];
for(int i = 0; i < 2; i++)
{
  sol[i] = i*i;
}

return max(sol[0], sol[1]);

Upvotes: 3

Related Questions