Saving variable names in array to use in FOR loop for EEPROM

Hi all,

i have a long list of variables i want to save and load using EEPROM. Currently i am saving and loading each variable by the method shown below...

  uint16_t totalBytes = 0;

  EEPROM.put(totalBytes, var1);
  totalBytes += sizeof(var1);
  EEPROM.put(totalBytes, var2);
  totalBytes += sizeof(var2);
  EEPROM.put(totalBytes, var3);
  totalBytes += sizeof(var3);

What i'd like to do is create an array with all of the variable names in it and then substitute those names into the code. That way i could do something like this...

string arrayNames[] = {"var1", "var2", "var3", "etc"};
uint8_t numberOfVariables = 10;
uint16_t totalBytes = 0;

for (int i = 0; i < numberOfVariables; i++) {
  EEPROM.put(totalBytes, arrayNames[i]);
  totalBytes += sizeof(arrayNames[i]);
}

I realise that the EEPROM.put will just save the value of "var1", "var2" etc to the EEPROM and the sizeof() will just tell me the size of arrayNames[i]. Is there any way to make the compiler read the text as a variable name and not just treat it as a variable in it's own right.

There would be lots of benefits to doing it the second way and not the first way but despite a lot of Google searching i can't find if this is possible or not. I used to code PHP and this sort of thing was possible in that language which is why i had the idea to try it in Arduino as well.

If this just isn't possible it would be good to know so i can stop searching and leave my code as it is.

Cheers

NM

the easiest way is to put all your variables you want to store in a stuct and put/get that struct in EEPROM

(note as well that at run time there is no concept of "variable name", it's all gone when you compiled. So you can't ask the compiler to store something by name)

if you are on an ESP32, the Preferences library supports key/value pairs so that could be closer to variable name / value

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.