While and condition tests

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 a 'while' the condition is tested before each time the body is executed:

while (!flag) doStuff();
acts like:

  while (true) // Repeat forever
  {
    if (flag) break;  // Leave the loop
    doStuff();
  }

If you want the test AFTER the body, use 'do-while':

  do
  {
    doStuff();
  } while (!flag);

acts like:

  while (true) // Repeat forever
  {
    doStuff();
    if (flag) break;  // Leave the loop
  }

The code inside 'doStuff()' makes no difference at all. All that matters is the value of 'flag' when the test is done.

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.

Thanks everyone!

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