Difference between “while” loop and “do while” loop

前端 未结 16 1101
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-13 06:44

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 {
                


        
16条回答
  •  感情败类
    2020-12-13 07:20

    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.

提交回复
热议问题