Goto and the folly of dogma

1    11 Jan 2018 21:23 by u/TheBuddha

5 comments

0

I have had many people sneer when they see a goto in my code. But usually it's in some triply nested loop that I just want to exit simply, and I always keep the goto within the scope of the function itself.

0

Exiting out of nested loops is really the only excuse I've seen for using gotos, but it's still a valid reason to use a goto. The alternative is to use some sort of exit flag that you set when you want to exit and check at each loop, but that can get just as messy, if not more, than just setting a goto to break out of the loops.

Perhaps a valid alternative would be to provide a numerical variable to break to specify how many levels you want to break out of, e.g. break(2) to break out of a double-nested loop. I wonder if this has ever been attempted?

0

What a beautiful and simple solution.

0

Are you referring to the break(n) idea ? (n being the number of loops to exit). Or, I was thinking further on it, perhaps have a way to label loops as well so that you can explicitly refer to what loop to break. Like:

loop1: for(int i = 0; i < num1; i++) {
    loop2: for(int j = 0; j < num2; j++) {
        if(a[i][j] == 'X') break(loop1);
     }
}

Honestly I've never felt a non-awkward way of handling the breaking out of nested loops. As I said, exceptions can be used to break out of a nested loop, but an error code isn't necessary an exception but could just be an expected condition telling us that processing is done, for example. In most of my code of that nature I use an extra boolean to indicate an exit condition, which I check at each loop level which I want to break out of. For example:

bool done = false;
for(int i = 0; i < num1 && !done; i++) {
    for(int j = 0; j < num2 && !done; j++) {
        if(a[i][j] == 'X') done = true;
     }
}

But it seems so much messier, especially if there are more than one loops or exit conditionals.

I'm honestly surprised that I've never come across any articles discussing this before, as I feel this is one of the few things in programming that has just always felt as if it's never had an elegant solution.

0

My coworker says that the use of break and continue display a poor command of conditional logic, but I think they have a purpose and can make code a lot cleaner. He would love your second example and praise it as "The most correct solution". We always argue about that kind of stuff.

As a side note I brought up the parameterized break idea and my boss said it could be very useful for continue as well. I wonder how deeply embedded these keywords are in the actual language itself. Any time I catch myself thinking "Oh! All they would have to do is X", I immediately realize that the problem is infinitely more complex than I understand at the moment.

Have you looked in to Jonathan Blow's new language that he is building? I might try to ask him on his stream what he thinks about the idea.