Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is

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

exactly like

while(a)
{
    b();
}

?

like image 842
user1365010 Avatar asked Jun 19 '12 13:06

user1365010


2 Answers

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.

like image 79
Frank Visaggio Avatar answered Sep 24 '22 03:09

Frank Visaggio


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.

like image 26
deceze Avatar answered Sep 21 '22 03:09

deceze