Tell HN: I've Just Discovered The Power Of Goto
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 ] threadThe person following you may not see it that way.
I fear that jumps may interact poorly with RAII. But I haven't been a C++ language-lawyer since the CFront days.
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.
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.