Replacing break and continue with structured equivalent

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • puneetsardana88
    New Member
    • Aug 2009
    • 57

    Replacing break and continue with structured equivalent

    Hi

    Is there any way by which we can replace break and continue with structured equivalent.

    We can cause loop continuation test to fail but break exits immediately from the point it is encountered so the statements after it are not executed.

    Eg

    int i=1,j;
    for(j=0;j<10;j+ +)
    {
    break;
    i++;
    }

    I can replace this as

    for(j=0;j<10;j+ +)
    {
    j=11;
    i++;
    }
    But i is incremented in second case. I am struck in this. Please help
  • donbock
    Recognized Expert Top Contributor
    • Mar 2008
    • 2427

    #2
    Consider the following abstract code snippet ...
    Code:
    while (not primaryTermination) {
       block1;
       if (secondaryTermination)
          break;
       block2;
       if (skipCondition)
          continue;
       block3;
       }
    The break and continue statements can be eliminated as follows. There are many similar variants.
    Code:
    while (not primaryTermination) {
       block1;
       if (secondaryTermination) {
          primaryTermination = true;
          }
       else {
          block2;
          if (not skipCondition) {
             block3;
             }
          }
       }
    Whether this results in better code is in the eye of the beholder.
    Last edited by donbock; Jun 14 '11, 12:20 PM. Reason: Added "not" to the while statement.

    Comment

    Working...