Exiting and Continuing Loops


Exiting and Continuing Loops

There are three commands that let you control the execution of loops: break, continue , and goto .

The break command enables you to exit the loop early. Rather than having to wait until a loop finishes, if you can determine that it isn't necessary to continue you can exit the loop.

The continue command lets you advance the loop at any point. Other languages like VB.NET don't offer this ability and so the entire loop has to be executed before advancing. With for loops, being able to advance the loop means that you can add one to the counter and go back to the beginning of the loop without having to execute the remaining statements.

C# enables you to assign labels to a segment of code in a function. You can then use the goto command to exit the loop and jump to a particular label in the code.

To use the break command:

  1. Inside the loop, type break .

  2. Type a semicolon ; ( Figure 3.41 ).

    Figure 3.41 In this example a number of items need to be copied from one directory to another. Ideally we want to move all the items, however, the user can cancel the copy midstream. If the cancel option is selected the break is invoked which causes the code to exit the loop.
     void CopyItems(int totalItems,              string src, string dest) {    for (int i = 0; i < totalItems; i++)    {       MoveFile(i, src, dest);       bool cancel = CheckUserCancel();       if (cancel)  break;  } } 

To advance the loop:

  1. Inside the loop type continue .

  2. Type a semicolon ; ( Figure 3.42 ).

    Figure 3.42 In the code below there is no sense doing anything if the item requested isn't in stock. Therefore, if the item isn't in stock, the code calls continue to go to the next item.
     void ProcessOrder() {    for (int i=0; i < items.Count; i++)    {       bool inStock = (GetItemQty(i) > 0);       if (inStock == false)  continue;  SubtractFromInventory(i);       SendToShipping(i);    } } 

To jump to another part of the code:

  1. First assign a label to the portion of code to which you would like to jump, for example: cleanup: .

  2. Inside the loop type goto followed by the name of the label, for example: goto cleanup ( Figure 3.43 ).

    Figure 3.43 You can put a label on a portion of the code. A label is a name followed by a colon . Then you can jump to that portion of the code with the goto command. You can only jump to labels in the same function.
     void DailyWorkRoutine() {    bool havingFun = true;    while (havingFun)    {       if (BossIsComing() == true)  goto fundone;  havingFun = CheckFunStatus();    }  fundone:  CloseBrowser();       ShutdownEmail();       DoActualWork(); } 

graphics/tick.gif Tips

  • If you have a loop inside of another loop, the break command only exits the inner loop ( Figure 3.44 ).

    Figure 3.44 When you have nested loops, the break statement only applies to the innermost loop in which it was executed. Incidentally, as you type the break; statement in VS.NET, VS.NET highlights the loop to which it belongs in bold.
     void PlanFoodForTrip(int totalFamilies) {    for (int i =0; i < totalFamilies; i ++)    {       for (int j = 0; j < famMembers(i); j++)       {          if (BringingFood(j))  break; //<--only exits inner loop  }    } } 
  • Sometimes there are too many conditions that may warrant exiting from a loop. When this happens developers normally write an infinite while loop. The infinite while loop has the clause while(true) which always evaluates to true, and therefore always executes the loop. When one of the many condition that warrant exiting is met, then you issue a break statement or a goto statement ( Figure 3.45 ).

    Figure 3.45 These types of loops are usually written when keyboard or mouse input needs to be monitored . The code continues to loop indefinitely until something calls break or goto.
     void TypeLetter() {    string msg = "";  while(true)  {       char c = GetKeyboardInput();       if (c=='q'  c=='x')  break;  else          msg += c;    }    Response.Write(msg); } 
  • Programmers typically stay away from goto statements, for one main reason: If goto statements are overused , the code becomes really hard to follow.




C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net