-2

Hello :D As a practice for Arduino, I'm trying to make a function that I can re-use to change global variables inside the loop function. So for example, I have two global booleans answer1 and answer2, and I have a void function that have boolean as an input. However, when I run the code, the global variables are not changing, and I'm sure what I am not understanding correctly.

bool answer1, answer2;

void setup() {
  answer1 = false;
  answer2 = false;
}

void loop() {    
  grading(answer1);
  grading(answer2);
}

void grading(bool _answer)
{
  _answer = true;
}
JBUG
  • 3
  • 1
  • Use references: `bool & _answer` as variables are passed by copy by default so you are changing copy of the original variable. Or maybe `bool grading() { return true; }` and `answer1 = grading();` but it might be oversimplified example so it might not be applicable. – KIIV Jul 23 '20 at 10:32
  • Or you can program it in C. – TomServo Jul 23 '20 at 21:37
  • Thank you so much for the comments :D I realized that I was just getting the copy of the variable with the function and call by reference was what I needed :D. – JBUG Jul 24 '20 at 08:33

1 Answers1

1

Use references.

bool answer1, answer2;

void setup() {
  answer1 = false;
  answer2 = false;
}

void loop() {    
  grading(answer1);
  grading(answer2);
}

void grading(bool& _answer)
{
  _answer = true;
}

...or pointers.

bool answer1, answer2;

void setup() {
  answer1 = false;
  answer2 = false;
}

void loop() {    
  grading(&answer1);
  grading(&answer2);
}

void grading(bool* _answer)
{
  *_answer = true;
}
Ihor Drachuk
  • 1,265
  • 7
  • 17