Is
if(a)
{
do
{
b();
}
while(a);
}
exactly like
while(a)
{
b();
}
?
Is
if(a)
{
do
{
b();
}
while(a);
}
exactly like
while(a)
{
b();
}
?
Yes, they're the same.
You've created a very unreadable way to mock the while
loop with do-while
loop + if
.
You should read this:
Test loops at the top or bottom? (while vs. do while)
Use while loops when you want to test a condition before the first iteration of the loop.
Use do-while loops when you want to test a condition after running the first iteration of the loop.
Yes, they're equivalent.
If a
is false
, b
will not execute at all.
If a
is true
, b
will execute until a
becomes false
.
This is equally true for both constructs.
They are the same and I will provide an example where you might actually want to use the "Do-While" instead of a while loop.
do{
x = superMathClass.performComplicatedCalculation(3.14);
}
while (x < 1000);
as opposed to
x = superMathClass.performComplicatedCalculation(3.14);
while ( x < 1000);
{
x = superMathClass.performComplicatedCalculation(3.14);
}
The argument for using a Do-While is shown above. Assume the line x = superMathClass.performComplicatedCalculation(3.14);
wasnt just one line of code and instead was 25 lines of code. If you need to change it, in the do while you would only change it once. In the while loop you would have to change it twice.
I do agree do whiles are off and you should avoid them, but there are arguments in their favor also.
The constructs are pretty much interchangeable in this case, but I think the if do while loop is useful in some cases, for example if some variables need to be kept through all iterations of the loop, but are not needed if the loop is never executed. (And it is assumed that it might not be.) 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 that object is time or memory intensive, and it is expected that this loop will only trigger occasionally and will be skipped in most executions of the relevant method. Of course there are other cases where it could be useful as well, basically I think the if-do-while should be used if there are things that should be executed before your loop starts, only when your loop is entered.