I am trying to change thing2
if I input 0, and thing3
if I input 1. I don't want to just have if/else to determine if I should be changing thing2
or thing3
because I want this to be more dynamic than that.
This is the code I currently have, it doesn't work because it is just changing the parts of thing1
instead of the variables. I am very lost and any help would be greatly appreciated.
String thing1[2] = {"thing1", "thing2"};
int thing2 = 10;
int thing3 = 0;
String function(int thingy, int thinggy) {
thing1[thingy] = thinggy;
Serial.println(thing1[thingy]);
return thing1[thingy];
}
void setup() {
Serial.begin(9600);
function(0, 10);
function(1, 20);
}
1 Answer 1
The easiest option may be to update those variables through an array of pointers. You create an array of pointers referencing all the variables you want to update in this manner, then you can index the array to access the variables:
// The variables that need to be updated.
int foo = 12;
int bar = 23;
int baz = 34;
// The array of pointers and its length.
const int variable_count = 3;
int * const variables[variable_count] = {&foo, &bar, &baz};
void update_variable(int which, int value) {
if (which < 0 || which >= variable_count) {
Serial.println("update_variable: bad index");
return;
}
*variables[which] = value;
}
void setup() {
Serial.begin(9600);
update_variable(0, 120); // foo <- 120
update_variable(1, 230); // bar <- 230
update_variable(2, 340); // baz <- 340
update_variable(3, 450); // bad index
Serial.print("foo = "); Serial.println(foo);
Serial.print("bar = "); Serial.println(bar);
Serial.print("baz = "); Serial.println(baz);
}
void loop(){}
if
orswitch
statements would go.it doesn't work because it is just changing the parts of thing1
... thing1 contains two variables