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?


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.


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]);