Blocking while?

Will StuffB be done exclusively (and blocking) as long as checkCondition = true?

void loop()
{
  doStuffA();
  test();
}

void test()
{
  while(checkCondition()) {
    doStuffB();
  }
  doStuffC();
}

Yes while() is a blocking function.

while is not a function. It is a kind statement, sometimes called a loop or while loop. Because it loops.

The way while works is the way it works.

"while" the condition part is true, execute the body statement, which may well be a compound statement, that is to say statements within { braces }.

Ppl often enclose a simple statement in { braces }. In case something is added later, it is easy to forget to gather up multiple statements into a compound statement.

a7

https://www.learncpp.com/cpp-tutorial/introduction-to-loops-and-while-statements/

Yes.

But this may not be a problem, depending on what checkCondition() and doStuffB() do.

For example, if they are searching through an array to find a value that meets some criteria, that's probably ok (unless the array is very large). It's ok because it will finish executing quickly, allowing doStuffA() and doStuffC() to run shortly after.

If they are waiting for some external event like pressing a button or receiving data from Serial, that's a problem. Then, the while loop will block for a long time, preventing doStuffA() and doStuffC() from running.

You can test such things on your own with serial printing
here is a link to a WKWI-simulation

best regards Stefan

You may have already more answers than you wanted :wink:

Anyhow, this is how I would solve it:

void loop()
{
  test();
}

void test() {
  static boolean firstEntry = true;
  static boolean callStuffC = false;
  if (firstEntry) {
    firstEntry = false;
    doStuffA();
  }
  if (checkCondition()) {
    doStuffB();
    callStuffC = true;
  } else {
    if (callStuffC) {
      callStuffC = false;
      doStuffC();
    }
    doStuffA();    
  }
}

The "firstEntry" boolean is only there to achieve a first doStuffA() after entering loop(). This could also be solved by moving the first call to setup():

void setup() {
  doStuffA();
}

void loop()
{
  test();
}

void test() {
  static boolean callStuffC = false;
  if (checkCondition()) {
    doStuffB();
    callStuffC = true;
  } else {
    if (callStuffC) {
      callStuffC = false;
      doStuffC();
    }
    doStuffA();
  }
}

The first approach can be tested on Wokwi (the delay() in the example is just there to reduce the serial output):

https://wokwi.com/projects/365513181279869953

This way you can add further functions to loop() which will be executed and not blocked by the other functions.

It is kind of a simple state machine with the states "true" and "false".

Top! I did not know this one, very useful.