Thread: How to exit from nested loops?

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Jun 2010
    Posts
    182

    Question How to exit from nested loops?

    Hi everybody.

    If I have nested loops, and I'd like to exit all of them given a condition,
    How do I break out?

    Code:
    for (x = 0; x < lim0; x++){
        for (x1 = 0; x1 < lim1; x1++){
            for (x2 = 0; x2 < lim2; x2++){
                 if (contidion)
                     break; // this exit the inner loop only - 
           }
        }
    }
    I don't know if C has got some exit or anything that suites the case,
    the only alternatives I see at the moment are return if I put the nested
    loops in a function, goto that is badly considered in modern world
    or to change the whole structure of the program, and that could be quite heavy
    to digest.

    Or I could use a workaround:
    Code:
    for (x = 0; x < lim0; x++){
        for (x1 = 0; x1 < lim1; x1++){
             for (x2 = 0; x2 < lim2; x2++){
                   if (contidion){
                       break_x1 = 1;
                       break_x = 1;
                       break; // this exit the inner loop only
                    }
             }
             if (break_x1) break;
         }
          if (break_x) break;
    }

    Any alternative in standard C99?
    Last edited by frktons; 07-17-2010 at 05:43 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need help in C programming (too lazy)
    By cwillygs in forum C Programming
    Replies: 12
    Last Post: 04-20-2010, 12:23 AM
  2. Displaying a table using nested loops
    By leviterande in forum C Programming
    Replies: 13
    Last Post: 09-29-2009, 04:42 PM
  3. Dynamic array of pointers
    By csisz3r in forum C Programming
    Replies: 8
    Last Post: 09-25-2005, 02:06 PM
  4. Evaluation of nested loops
    By Mister C in forum C Programming
    Replies: 2
    Last Post: 08-13-2004, 01:47 PM
  5. nested for loops
    By akub3 in forum C Programming
    Replies: 2
    Last Post: 04-01-2004, 06:21 AM