-1

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);
}
dda
1,5951 gold badge12 silver badges17 bronze badges
asked Jul 11 at 14:37
3
  • For a start, using more meaningful names, rather than "thing", might make the code clearer as well as the overall task that you are trying to achieve. Also think about where some conditional if or switch statements would go. Commented Jul 11 at 15:00
  • 1
    it doesn't work because it is just changing the parts of thing1 ... thing1 contains two variables Commented Jul 12 at 21:30
  • 2
    this looks like an XY question ... what is the actual problem that you are trying to solve? ... your current question is not related to the Arduino Commented Jul 12 at 21:32

1 Answer 1

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(){}
answered Jul 11 at 16:55

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.