Exit multiple loops without using goto

Asked

Viewed 182 times

4

Oops! The title says it all! Someone knows an interesting way to get out of more than one loop without using goto?

2 answers

6

Interesting not.

It is possible to use a long jump in C or make an exception in C++, but are much worse options than goto.

In some cases a simple return in a function can solve, so you place the code strategically to take advantage of it.

You can make the loop end with the creation of variable that controls it, is called flag, but it complicates the code a lot. It’s ridiculous how the code looks and how complicated it is to analyze and debug something like this. It gets much worse just to meet a silly artificial demand. People need to understand that it is not to use this command to improve the code, when it gets worse without it then it is to use. See in the above answer how bad it looks. With goto looks better:

for (int i = 0; i < 640; i++)
    for (int j = 0; j < 480; j++)
        for (int k = 0; k < 4; k++) {
            ...
            if (condition) {
                ...
                goto fim;
            }
        }
    }
}
:fim

I put in the Github for future reference.

It may seem bigger, but it’s only because in the other answer the code is incomplete. Try debugging both.

So, if you can’t create a situation that the tie closes naturally (always gives, but there is case that gets too confused and can be better to do artificially even) the best is to use the goto.

  • Leave it alone... I’ll use just the same...

5


In C it is possible to have a control variable that is part of the expression of for - you arrow it into the innermost loop, and this leaves false expressions of the most external loops. Only that the code after the end of the internal loop, but inside the external loops will run one last time, unlike what would happen with a goto or an exception.

int finished = 0;
for (int i=0; !finished && i < 640; i++)
  for (int j=0; !finished && j < 480; j++)
     for (int k=0; !finished && k < 4; k++) {
        ...
        if (condition) {
            ...
            finished = 1;
        }
     }
  • 1

    I think this solution is the most elegant. The "extra" execution to which you refer can be avoided, if desired, by adding a break or continue.

  • That’s a good one.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.