Thread: goto statement help

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Jan 2012
    Posts
    8
    How does this look? Is this right?

    Code:
    int i,pass;
       boolean swapMade;
    
       pass = 1;
       *numberCompares = 0;
       *numberMoves = 0;
    
    STARTOFDO:
       {
           swapMade = false;
           i = 0;
           FIRSTLOOP:
           if(!(i <= n-(pass+1))) goto END;
           {
               *numberCompares += 1;
               if(!(ShouldSwap(A[i],A[i+1]))) goto FIRSTLOOP;
               {
                   int T = A[i]; A[i] = A[i+1]; A[i+1] = T;
    
                   *numberMoves += 3;
                   swapMade = true;
               }
           }
           pass++;
       }if(!(swapMade)) goto END;
    END:

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Quote Originally Posted by lscamaro View Post
    How does this look? Is this right?
    Pretty close, check the comments in the code

    Code:
    int i,pass;
       boolean swapMade;
    
       pass = 1;
       *numberCompares = 0;
       *numberMoves = 0;
    
    STARTOFDO:
       {
           swapMade = false;
           i = 0;
           FIRSTLOOP:
           // The end of the for loop may not be the same as the end of the do, use two separate labels with good names and goto the right one
           if(!(i <= n-(pass+1))) goto END;
           {
               *numberCompares += 1;
               // Next line is wrong, you skip the increment.  Just use the if condition as it was before (no !) without a goto
               // if (ShouldSwap(...))
               if(!(ShouldSwap(A[i],A[i+1]))) goto FIRSTLOOP;
               {
                   int T = A[i]; A[i] = A[i+1]; A[i+1] = T;
    
                   *numberMoves += 3;
                   swapMade = true;
               }
           }
           pass++;  // This should be i++
           // Don't forget to go back to the start of the for loop here
    // This is where your END_FOR_LOOP label would go
       }if(!(swapMade)) goto END;  // The do loop needs to continue if swapMade is true, try: if (swapMade) goto STARTOFDO
    END:

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Trouble using GOTO with the SWITCH statement!
    By xxJaRxx in forum C Programming
    Replies: 9
    Last Post: 03-10-2010, 06:42 AM
  2. GOTO statement in c++
    By kibestar in forum C++ Programming
    Replies: 8
    Last Post: 03-22-2009, 07:10 PM
  3. goto statement interpretation in VC 6 and 7
    By w262 in forum C++ Programming
    Replies: 2
    Last Post: 02-28-2005, 10:37 PM
  4. Goto statement
    By _JjC:: in forum C Programming
    Replies: 2
    Last Post: 03-02-2003, 10:43 AM
  5. but why not GOTO?
    By LonelyPlanetWanderer in forum C Programming
    Replies: 13
    Last Post: 12-24-2001, 11:46 AM