"while" inside "if" loop: precedence?

If a "while" inside an "if" loop gets resolved (ie. the "while" is exited), and meanwhile the conditions of the enclosing "if" are not valid anymore: does the rest of the code after the "while" but inside the "if" loop get executed?

if (x == 0)
{
   while (y == 0)
      {
      // do whatever
      }
   z=digitalRead(i);
}

For example, y suddenly is not equal to 0 anymore, the "while is exited, and meanwhile also x is not equal to 0 anymore: is the digitalRead being executed?

The code following the while, in your example

z=digitalRead(i);

will be executed when the while loop ends no matter what the value of x at that time, even if the value has changed in the meantime, because the code does not test its value again at that point

What problem are you trying to solve ?

1 Like

There is nothing like an if loop, if is a conditional statement. If the condition is true then the body of the statement is executed. In your case the digitalRead() is the last statement of the body and thus is executed before the body is left.

1 Like

Great! Thanks a million for something that should have been obvious except for me :slight_smile:

Hi UKHeliBob, this was for a software debounce (while waiting for a button to be released before taking further action), but following an earlier question here I abandoned the use of while; however I still had the lingering doubt about the sequence of events when using the while.

The rule is, statements are executed sequentially. So the statement following a conditional statement exit, is the one that is executed.

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