do..while inquiry

danieltsz

Well-known member
Hi, i have a simple question regarding the do whle loop using teensy board.

Code:
int x;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  do {
    Serial.println(x);
    x++;
    delay(1000);
  } while (x < 5);
}

void loop() {
  // put your main code here, to run repeatedly:
}

Using the code above, Serial monitor displays 0-4, but when i move the do while code inside void loop, it continues to run the program even after x=5

Code:
int x;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  do {
    Serial.println(x);
    x++;
    delay(1000);
  } while (x < 5);
}

I don't know what I'm doing wrong with my simple test code for do while loop
 
As those comments in the code try to explain, the setup() function runs once. Then the loop() function runs repeatedly.

The first time loop() runs, it will print 5 numbers.

Every subsequent run of loop(), it will print 1 more number. This is the nature of do-while. The code after "do" always executes at least once. The "while" check is performed after the code as run. So each time loop() runs, the variable "x" will be printed and incremented again. The "while" condition will never be true after that first time loop() runs. But with do-while, even if the "while" condition is false, the code executes at least once. Combined with loop() being called over and over, your program continued printing indefinitely.
 
Also it's good practise to initialise your x variable to 0 when declaring it.

It could be placed in a piece of unused memory that had a value. I've been caught out with this before.
 
Also it's good practise to initialise your x variable to 0 when declaring it.

It could be placed in a piece of unused memory that had a value. I've been caught out with this before.

In this case, x will be initialized to 0. Global non-static variables that are not explicitly initialized are all initialized to 0 at runtime (before main is called).
 
or
Code:
while(x<5) {
...
}

which is even less typing
Not really
Option 1
Int x;
x++;
do {
while {x < 5}

Option 2
For(int x = 0; x < 5; x++){
}

Its spread over multiple lines. You have also got a global variable that is only ever used once.
 
Back
Top