Tell HN: I've Just Discovered The Power Of Goto

4 points by optimalsolver ↗ HN
Where has it been all my life?

It's just solved a bunch of hard control-flow problems in my C++ code, and I'm kicking myself for having let people scare me off using it.

Moral of the story: Try things for yourself. Ignore the greybeards.

Also, found this XKCD while researching it:

https://xkcd.com/292/

9 comments

[ 3.1 ms ] story [ 32.3 ms ] thread
No one ever said that GOTO wasn't powerful...
> It's just solved a bunch of hard control-flow problems in my C++ code

The person following you may not see it that way.

In Powerbuilder language, there was no decent exception handling, I used return codes and goto in almost every function, like you can do in C.
I do think there are a few legitimate uses in straight C code, usually in a multiple error exit condition with cleanup situation, or to break out of multiple levels of nested loop without adding flags. I myself was indoctrinated hard into structured programming early on and so I cannot bring myself to use it but reading other people's code, I don't mind it if it is used in one of these cases and the flow is clear.

Actually I do mind - I'd like to see C with some additional control structures. I wrote a bit about this in a blog post a few years ago: https://thepottshouse.org/paul/the_books_that_wrote_me_blog/...

Also, I feel like many developers never learned do/while and continue, or the variations that are possible in a for loop other than just incrementing and testing a single variable, and their code can often be simplified using these things while removing goto.

It doesn't seem like it is at all idiomatic in C++ so I'd be curious to see what you're doing. As another poster mentioned it would certainly interact poorly with RAII, but not all code needs or uses RAII in all functions.

This graybeard has just never found himself needing or wanting a goto. Not since he coded in BASIC on his Osborne 1, which tells you just how gray his beard is.

I did once find myself using the continue <label> construct -- once. It was so unusual that I remember it. And was also unsurprised when a subsequent refactoring eliminated it.

I have occasionally found myself with something ugly. Maybe a goto would have cleaned it up, if I'd considered it. But in the end, that code got written without the goto, and was probably better for it. Somebody else would have had to look at that code some day, and I know that goto is so hard to reason about that they would have found it very difficult to maintain.

In the end, your primary motivation is that your code works. If the code smells, then it smells. Just remember that your secondary motivation is that your code also has to be maintained -- possibly by someone else, and possibly by you after you've forgotten what assumptions went into that goto.