When using a while loop to check a variable within a function, when exactly is the variable tested?
From what I can see, it is only tested a the end of each iteration of the function. So only in position #3.
Is that correct?
bool flag = false;
void loop()
{
while (!flag) doStuff();
Serial.println("done");
}
void doStuff()
{
flag = true; // #1
// someCode
flag = true; // #2
// someMoreCode
flag = true; // #3
}
Sort of. More clearly, it's done within the context of the while() structure, but after return from the function call. So not quite where you're describing.
Not exactly. doStuff must complete in it's entirety and return before the while test happens again, so #3 is the line that is effective, but the others would have had the same effect if you had omitted it.
In my case, the code in doStuff() does make a difference as flag can be changed in one of two places - either by the flag = true; statement or within // someCode.
I was trying to figure out why the sketch didn't do what I wanted, and the while test seemed to be the culprit. So it's good to have that confirmed.