Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Breaking out of nested infinite while loops. (http://www.go4expert.com/forums/breaking-nested-infinite-loops-t20102/)

Player 15Nov2009 21:20

Breaking out of nested infinite while loops.
 
Can anyone tell me how to do as the title says? I'm told that using goto is a no no. Here is some sample code that i can't seem to be able to figure out. I'm a novice by the way ;)
Code:

#include<stdio.h>

int main(void)
{
        while(1)
        {
                printf("Hello.\n");
                while(1)
                {
                        while(1)
                        {
                                printf("How do i break out of this loop and back into the Hello loop?\n");
                        }
                }
        }
return(0);
}


Gene Poole 15Nov2009 21:44

Re: Breaking out of nested infinite while loops.
 
The "break" keyword will break you out of the loop:

Code:

  while(1){
    printf("Stuck in the loop\n");
    if(somecondition){
      break;
    }
  }
  printf("Broke out of the loop\n");


Player 15Nov2009 23:51

Re: Breaking out of nested infinite while loops.
 
Hi. I know about break. How do you break from a multiple loop. Look at my example again. :)

Gene Poole 16Nov2009 03:02

Re: Breaking out of nested infinite while loops.
 
You'll have to use multiple breaks.

Player 16Nov2009 19:48

Re: Breaking out of nested infinite while loops.
 
My way :)
Code:

#include<stdio.h>
#define TRUE 1
#define FALSE 0

int main(void)
{
        short int exitloop;
        while(1)
        {
                exitloop=FALSE;
                printf("Hello.\n");
                while(1)
                {
                        while(1)
                        {
                                printf("This is how i break this loop, back into the Hello loop\n");
                                exitloop=TRUE;
                                break;
                        }
                        if(exitloop==TRUE)
                                break;
                }
        }
return(0);
}


xpi0t0s 17Nov2009 21:03

Re: Breaking out of nested infinite while loops.
 
The correct answer depends very much on what you are trying to do. Nesting three infinite loops isn't a practical design for anything I've come across. Let us know what problem you're trying to solve and we'll see if we can come up with a better solution.

On the other hand if this is just for academic interest, yeah, just use a goto, whatever works. Makes no difference.


All times are GMT +5.5. The time now is 00:51.