Is
if(a)
{
do
{
b();
}
while(a);
}
exactly like
while(a)
{
b();
}
?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With