Is if () {do {}; while ();} just like {}

there is

if(a) { do { b(); } while(a); } 

exactly like

 while(a) { b(); } 

?

+6
source share
5 answers

They are the same, and I will give an example where you might want to use "Do-While" instead of a while loop.

 do{ x = superMathClass.performComplicatedCalculation(3.14); } while (x < 1000); 

Unlike

 x = superMathClass.performComplicatedCalculation(3.14); while ( x < 1000); { x = superMathClass.performComplicatedCalculation(3.14); } 

The argument for using Do-While is shown above. Suppose the line x = superMathClass.performComplicatedCalculation(3.14); there wasn’t just one line of code, but instead there were 25 lines of code. If you need to change it, do it while you only change it. In a while loop, you have to change it twice.

I agree that you should leave, and you should avoid them, but there are arguments in your favor.

+1
source

Yes, they are the same.
You created a very unreadable way to trick a while with a do-while + if do-while .

You should read the following:
Check hinges on top or bottom? (while vs. do while)

Use while if you want to check the condition before the first iteration of the loop.

Use do-while tags if you want to check the status after starting the first iteration of the loop.

+1
source

Yes, they are equivalent.
If a is false , b will not execute at all.
If a true , b will execute until a becomes false .
This is equally true for both designs.

+1
source

In this case, the constructs are largely interchangeable, but I think that the while if while loop is useful in some cases, for example, if some variables need to be saved through all iterations of the loop, but not needed if the loop never runs. (And it is assumed that this may not be so.) For example

  if (condition) { LargeComplexObject object = new LargeComplexObject(); do { some action ... object.someMethod(); ... more actions } while (condition); } 

This can be a useful optimization if the initialization of this object depends on time or memory, and it is expected that this cycle will be run only occasionally and will be skipped in most cases of the corresponding method. Of course, there are other cases where this can be useful, basically, I think if-do-while should be used if there are things that should be done before the loop starts, only when your loop is introduced.

+1
source

Yes , but you should prefer the latter.

0
source

Source: https://habr.com/ru/post/918475/


All Articles