0

This is my code:

while(true){
    for(int x = 0; x < 10; x++){
        StringArray[x] = new string();
        if(isDead){
            break; //break out of while loop also
        }
    }
}

How should i do this please, sorry if my english is good,i still learning.

7 Answers7

3

Change your while loop to a variable, then set that variable to false (your isDead variable for instance)

while(!isDead){
    for(int x = 0; x < 10; x++){
        StringArray[x] = new string();
        if(isDead){
            break; //break out of while loop also
        }
    }
}

That way, your break will get you out of the for loop, then having the isDead set to true will stop the while loop executing.

Steve
  • 9,335
  • 10
  • 49
  • 81
1

create a function inline, and call it. use return from within the lambda.

var mt = () => {
    while(true){
        for(int x = 0; x < 10; x++){
            StringArray[x] = new string();
            if(isDead){
               return
            }
        }
    }    
}
mt();
Peter Aron Zentai
  • 11,482
  • 5
  • 41
  • 71
1

So as I understand you wanted to break 2 Loops on one condition. You can do the following

bool DirtyBool = true;
while(DirtyBool)
{
    for(int x = 0; x < 10; x++)
    {
        StringArray[x] = new string();
        if(isDead)
        {
            DirtyBool = false;
            break; //break out of while loop also
        }
    }
}
Mohit S
  • 13,723
  • 6
  • 34
  • 69
0

You could create a bool for example:

bool leaveLoop;

And if isDead is true then set leaveLoop to true, in the while loop then check if the leaveLoop is true to break from it.

Nicholas Ramsay
  • 465
  • 2
  • 16
0

Try below:

bool bKeepRunning = true;
while(bKeepRunning){
    for(int x = 0; x < 10; x++){
       StringArray[x] = new string();
       if(isDead){
         bKeepRunning = false;
         break; 
    }
    }
}
David
  • 15,894
  • 22
  • 55
  • 66
0

My favorite approach to this sort of situation is to move the code into a separate routine and simply return from it when I need to break. Two loops is as much complexity as I like to include in a single routine anyway.

Loren Pechtel
  • 8,945
  • 3
  • 33
  • 45
0

You can use goto:

    while(true){
        for(int x = 0; x < 10; x++){
            StringArray[x] = new string();
            if(isDead){
                goto EndOfWhile; //break out of while loop also
            }
        }
    }
EndOfWhile: (continue your code here)
mohammad
  • 1,248
  • 3
  • 15
  • 27