What is the difference between while loop and do while loop. I used to think both are completely same.Then I came across following piece of code:
do {
do while in an exit control loop. while is an entry control loop.
while(wdlen<2){
...
}
If wdlen (assuming it's a stack variable) is not initialized or assigned a value before the while loop is entered, it will contain whatever was in that space in memory before (i.e. garbage). So if the garbage value is < 2, the loop executes, otherwise it doesn't.
do{
...
}while(wdlen<2)
will execute once and then checks on condition to run loop again, and this time it might succeed if by chance wdlen which is uninitialized is found to be less than 2.
while test the condition before executing statements within the while loop.
do while test the condition after having executed statement within the loop.
source: let us C
The most important difference between while
and do-while
loop is that in do-while
, the block of code is executed at least once, even though the condition given is false.
To put it in a different way :
In WHILE first check the condition and then execute the program In DO-WHILE loop first execute the program at least one time then check the condition
The difference is in when the condition gets evaluated. In a do..while
loop, the condition is not evaluated until the end of each loop. That means that a do..while
loop will always run at least once. In a while
loop, the condition is evaluated at the start.
Here I assume that wdlen
is evaluating to false (i.e., it's bigger than 1) at the beginning of the while
loop, so the while loop never runs. In the do..while
loop, it isn't checked until the end of the first loop, so you get the result you expect.