I mean, with the same code, if I modify a do while into a while in this way:

do {$S;$} while ($B$) into a $S;$ while ($B$){$S;$} , there is any change in the code?

B = condition

S; = instructions

  • 1
    $\begingroup$ Do you have any thoughts? $\endgroup$ – Raphael Oct 6 '17 at 23:09

While and do while differ only in the first execution when condition is false. If you ignore this difference it boils down to the place of condition check, in while the condition is checked and if it is true the statements are executed. In the do while the condition check is executed after the block execution.

The code is exactly the same, with one line reordered.

If you want to do micro-optimisations please check whether these are worthy of your time. Compiler does really great job nowadays, unless it doesn't then change the compiler.

So under the hood they are equivalent.

| cite | improve this answer | |
  • 4
    $\begingroup$ I would add that the while version of the code has code duplication, which is often a place where bugs creep in, if you need to change the code, you change one version and not the other. $\endgroup$ – Dave Clarke Oct 6 '17 at 17:44
  • 3
    $\begingroup$ @AntonioM.Burgueño In while you wrote S two times. Let's say you want to change S to S1 in do..while you have to change only one block, in while you have to change both blocks. If you forget one, you have a bug. $\endgroup$ – atakanyenel Oct 6 '17 at 21:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.