0

I'd like to initialize a bunch of variables by calling them in a for loop like this. The effect I'm hoping for is that I'd have three variables at the end aVar = 1, bVar =2, and cVar = 3.

char* variables[] = { "aVar", "bVar", "cVar"};
int values[] = { 1, 2, 3};

void setup(){
  for (int i = 0; i < 3; i++){
    int String(variables[i]) = values [i];
    Serial.println(variables[i]);
  }
}

Is there a way to do this?

flomerboy
  • 1
  • 1

1 Answers1

1

What you seem to be suggesting is creating a variable at run time whose name is also variable which is not possible. What you could do is create a map and have your keys be entries from variables array and your values be entries from values array.

using namespace std;
int main()
{
  char* variables[] = { "aVar", "bVar", "cVar"};
  int values[] = { 1, 2, 3};
  map<string, int> VariablesMap;
  for(int i  = 0; i < 3 ; i ++)
  {
     VariablesMap[variables[i]] = values[i];
  }
  return 0; 
}
KnightFox
  • 3,132
  • 4
  • 20
  • 35