Search code examples
c#breakcontinue

Is there a better way of exiting the loop than goto?


I have a very large loop that loops a 1000 rows. I exit the loop if magic value 1 is found. If magic value 1 is not found but magic value 2 is found then the loop needs to skip to the beginning. Right now I am using a switch, some ifs and a goto. I have read that goto is not the best way. Is there a better way to make this work?


Solution

  • To exit a loop you can use the break statement, to go onto the next record you can use the continue statement.

    for(int i = 0; i < 1000; i++)
    {
        if(magicValue1)
           break;
        if(magicValue2)
           continue;
    }
    

    I AM NOT CONDONING THE USE OF THE GOTO STATEMENT I AM SIMPLY POINTING OUT A POSSIBLE USE CASE

    You can use goto jump statement to start/exit a loop, however I would stay away from this option unless you are using nested looping. I think the goto statement still has its uses for optimizing, exiting cleanly ect.. but in general it is best to use it quite sparingly.

    for(int i = 0; i < 100; i++)
    { 
      start:
    
      for(int i = 0; i < 10; i++)
      {
         if(magicValue1)
           goto end;
        if(magicValue2)
           goto start;
      }
    }
    end :