Is using goto a legitimate way to break out of two loops?

前端 未结 6 866
悲哀的现实
悲哀的现实 2021-01-01 16:05

I am solving problem 9 on the Project Euler. In my solution I use a "goto" statement to break out of two for loops. The Problem is the following:

6条回答
  •  孤独总比滥情好
    2021-01-01 16:26

    See this question about breaking out of 2 loops. There are much better answers provided than using a goto.

    The best answer provided is to place your second loop into a function, and call that function from inside your first loop.

    code copied from mquander's response

    public bool CheckWhatever(int whateverIndex)
    {
        for(int j = 0; j < height; j++)
        {
            if(whatever[whateverIndex][j]) return false;
        }
    
        return true;
    }
    
    public void DoubleLoop()
    {
        for(int i = 0; i < width; i++)
        {
            if(!CheckWhatever(i)) break;
        }
    }
    

    Though I do feel that using a goto in this case isn't quite as bad as killing kittens. But it's close.

提交回复
热议问题