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

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.

Leave a Comment