Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 376
fedemengo Avatar asked Mar 25 '15 13:03

fedemengo


People also ask

Can you dynamically name a variable?

In programming, dynamic variable names don't have a specific name hard-coded in the script. They are named dynamically with string values from other sources.

What is dynamic variable in C?

A dynamic variable can be a single variable or an array of values, each one is kept track of using a pointer. After a dynamic variable is no longer needed it is important to deallocate the memory, return its control to the operating system, by calling "delete" on the pointer. Operation. Symbol.

What variable names are not allowed in C?

A variable name can start with the alphabet, and underscore only. It can't start with a digit. No whitespace is allowed within the variable name. A variable name must not be any reserved word or keyword, e.g. int, goto, etc.

How do I create a dynamic variable name?

Use an Array of Variables The simplest JavaScript method to create the dynamic variables is to create an array. In JavaScript, we can define the dynamic array without defining its length and use it as Map. We can map the value with the key using an array and also access the value using a key.


1 Answers

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.

like image 125
Andrew Avatar answered Sep 19 '22 04:09

Andrew