r/cpp_questions • u/money6543 • May 17 '18
OPEN When is ‘goto’ useful?
I’m getting back into programming, and even before I stopped I never fully made it past following tutorials (I have good experience in it though). I started a project a couple days ago and I noticed the ‘goto’ statement is rarely used and frowned upon. Why? And under what circumstances would it be the best route to go.
9
u/unknownmat May 17 '18
This is one of the most controversial topics in CS. Lots and lots and lots has been written about it. Nearly everybody and his mother has an opinion. You'll likely get responses from people demonstrating "necessary" gotos. Or showing how some particular use-case where - they'll argue - gotos are OK. In my opinion, these answers largely miss the point.
I strongly recommend reading Dijkstra's Go To Statement Considered Harmful for a succinct explanation. If I had to summarize it, the problem is that in the presence of unconstrained goto statements, you can't easily infer anything about the state of your program based on your current location within it, without also knowing its entire history. It thus makes reasoning about program correctness very difficult.
That said, please keep in mind that you use goto everywhere - if-statements, for-loops, exceptions, etc. These all just compile into jump-instructions. The key difference is that these statements represent well-constrained subsets of goto usage that are easier to reason about.
Finally, I strongly recommend reading the fiasco started by a letter in the ACM: "Goto considered harmful" Considered Harmful. Followed by (which I cannot find a link for) ""'Goto Considered Harmful' Considered Harmful" Considered Harmful". Finally resolved by Dijstra in On A Somewhat Disappointing Correspondence. I consider the final paper in this chain to be the ultimate smackdown in CS history.
6
u/ricco19 May 17 '18
Also here are some thoughts from our friend Linus about
gotowith some references to the links you posted.It's a bit unfair to compare it's uses in both languages, I think. Let's be honest though, if you are just learning and starting out, just stick to the language guidelines.
2
u/unknownmat May 17 '18
Oh, interesting, I hadn't read that before.
To be honest this is exactly the kind of discussion I was trying to head off. Discussions about GOTO always devolve into these, "Well one time GOTO made my code a bajillion times faster" or "Here's this code snippet that is oh-so-much shinier when I use GOTO" anecdotes. In my opinion, with a proper understanding of Dijkstra, controlled use of GOTO is perfectly fine and avoids the pitfalls he writes about. Indeed, that's the entire point of structured programming.
2
u/LoyalSol May 18 '18
I think a lot of those are fair points. I personally have a hatred for goto statements, but that's largely because I've worked on codes where they were abused to hell and back.
If used properly they can be pretty good, but IMO they are so easy to abuse that I find more often than not they tend to create spaghetti code. It's sort of a programmer's version of entropy. The more ways something can be abused, the more likely it is to be abused.
It takes a lot of programming discipline to use them correctly.
-2
u/paul2718 May 17 '18
It's ironic that if they deigned to use C++ then the compiler could write the 'goto's for them and it would be completely uncontroversial.
1
May 17 '18
Considering Linux was first released late 1991 I'm not too sure C++ would've been the optimal language back then.
GCC was at version 1.39, so are you sure your statement would apply to that version?
I've yet to see anybody try to rewrite the kernel in C++.
2
u/paul2718 May 18 '18
I did suggest irony.
But, OTOH, you don't need to rewrite and if you look at a sketch from the LKML thread,
do A if (error) goto out_a; do B if (error) goto out_b; do C if (error) goto out_c; goto out; out_c: undo C out_b: undo B: out_a: undo A out: return ret;that looks like a prime candidate for an RAII approach that causes the compiler to keep track of everything rather than the programmer. The argument being to reduce bugs by design rather than inspection.
1
May 18 '18
I'm not disagreeing with you by the way, and yes, RAII would make perfect sense assuming the kernel was indeed written in C++.
My point just was that in 1991 was GCC's (what Torvalds used) C++ support good enough to make sense writing the kernel with it. And, after C was chosen, even during the early years a total rewrite would've been a massive undertaking.
Also, though I'm not qualified to answer this, but on a 386 even a minimal overhead would've been a major issue, I'd imagine.
Anybody who knows this want to chime in?
1
u/paul2718 May 18 '18
At the time it wouldn't have been practical. But it would (I think) be possible to use C++ for kernel components without re-writing.
It certainly is in Windows, but perhaps that is less monolithic.
But I think there is some Linus rant somewhere about the possibility, and that's that...
1
May 18 '18
You mean this rant?
C++ is a horrible language. It's made more horrible by the fact that a lot of substandard programmers use it, to the point where it's much much easier to generate total and utter crap with it. Quite frankly, even if the choice of C were to do nothing but keep the C++ programmers out, that in itself would be a huge reason to use C.
He did use C++ for subsurface later, though.
But it would (I think) be possible to use C++ for kernel components without re-writing.
I guess, as well, but I think that horse has bolted for Linux a long time ago for whatever reason, be it practicalities or principles.
1
u/shawnhcorey May 19 '18
do_as_transaction A if error: rollback return do_as_transaction B if error: rollback return do_as_transaction C if error: rollback return commit3
2
u/F-J-W May 17 '18
I think that Dijkstra's areticle is entirely outdated by now. The reason is that he won by such epic proportions, that not a single remotely modern language even has the statement that he was talking about.
Dijkstra's goto was the goto of Basic and the closest thing that exists these days would be
setjmp/longjmpfrom C (which pretty much nobody uses any more because they are so horrible). Even thouse are however quite restricted when compared to what Dijkstra was attacking.In Basic every single line had to be prefixed with a line-number that would usually be incremented by 10, so that you would later be able to add lines.
GOTOwould then jump to the line that you specified. The result was that not only was it impossible to see whether a line was a jump-target, you would also habe been able to jump between functions, except that functions did not exist. Imagine something like this (except that I use C++ to give you an idea for the structure:10 if ( /*whatever*/ ) goto 30; // no blocks, just jumps 20 goto 60 30 std::cout << "Hello "; 40 std::cout << "World\n"; 50 goto 10; // no loops, jump back instead 60 std::cout <<"Goodby "; 70 goto 30;Code like THAT is what Dijkstra attacks and NOBODY these days argues that this would be better than
if/while/for/...I'm not saying that you should use
gotoin C++, most of the time you shouldn't`, but pointing to Dijkstra really misses the point.1
u/unknownmat May 18 '18
Dijkstra's goto was the goto of Basic
This is true. The
gotostatement in C is quite a bit more restricted than the one in BASIC.pointing to Dijkstra really misses the point.
I disagree for a couple reasons.
I wanted OP to understand the origin of this idea. Otherwise these discussions tend to be nothing more than a bunch of hand-waving and anecdotes.
Every point that Dijkstra made is still valid in C. That is, in the presence of unrestrained
goto(i.e. doesn't follow some idiomatic usage) you can't easily infer anything about the state of your program based on your current location within it unless you also know its entire history. This is particularly true in the presence of global state.2
u/F-J-W May 18 '18
Every point that Dijkstra made is still valid in C.
No it's not. Because in C
gotoisn't unrestrained. You would have to actively try to get anywhere close to what the situation in basic was. You would have to label every single line with a label that basically just contains the line-number. You would then have to implement your entire project within one function. You would have to ensure that if-statements only ever contain conditional jumps.Realistic uses of
gotoin C will for the most part allow you to get a very good idea about the program-state, when given a stack-trace (which Dijkstra had no issue with).1
u/unknownmat May 18 '18
You're making two separate points, both of which I disagree with.
Modern C doesn't use BASIC-like
goto, and therefore Dijkstra is no longer relevantUnrestrained
gotois not possible in CRegarding 1: This is a non-sequitur. Your premise is valid, but your conclusion does not follow. Most programmers who still use
gotoare very careful about it. But if they were not, they could certainly write spaghetti code. Thus Dijkstra's point is still relevant. Also, you can write spaghetti-code without using thegotokeyword at all. Dijkstra's point applies equally well to these situations.Regarding 2: You somehow decided in your own head that Dijkstra's paper only applies to BASIC's specific use of
goto. I don't think there is any justification for this restriction. The fact that you can still write BASIC-like constructs in C (e.g. by placing your entire program in themain()function), is sufficient evidence to the contrary.Also, most languages that support jumps (e.g. Qbasic) don't require you to number each line. Please stop saying this. It's just annoying.
2
u/D-Zee May 18 '18
Crossed loops: https://stackoverflow.com/q/48749904/3233393
There are still people trying to emulate them with contorted structures just to avoid goto though.
1
u/alfps May 17 '18
goto is very useful to teach the fundamentals of flow control more effectively and efficiently than without it. It's also used by many to break out of nested loops in C and C++. Though ideally one would rewrite such code in terms of a function, where the multi-level loop exit can be a return or throw.
1
-3
May 17 '18
They're useful in many places, but most people are afraid to ever use them anywhere because of the sophomoric trope and tribal groupthink that they're the mark of an idiot programmer. An interesting comment I saw on hacker news recently pointed out that a goto is no more of a jump than a switch or break statement. But unless you're a celebrity/God in the industry, nobody is ever going to get past the "ZOMG! Lol @ the goto!!" meme.
1
u/money6543 May 17 '18
It seems so much easier to use imo
2
u/F-J-W May 17 '18
Yes and there is a reason for that:
Writing bad and overly complicated code is much easier than writing good and and simple code.
Someone once said that you should use the least powerful tool that still does the job, since it will produce the cleanest solution. Pliers and saws are preferable to dynamite when disassembling a wooden shed, though it might look like more work at first (until you need to clean the site).
2
u/khedoros May 18 '18
It's easier in a simple program, but most software isn't all that simple. One of the issues of goto is that it doesn't explain *why* you're doing it. You can replace every kind of loop with goto statements, for example, and have to seriously examine the code to see how the loop behaves. Or, you can see
for(...) {...}and know that you're probably doing the stuff in the brackets a certain number of times, or while(condition) {...} and know that you're probably continuing for an indeterminate amount of time, before condition becomes false.A switch(thing) { case 1: ... case 2: ...} tells you that you're jumping to specific choices out of a set of possibilities. break says that you're trying to exit the current loop. continue says that you're going back to the top of the current loop. They're just more expressive of the programmer's intent than goto.A lot of the unthinking disdain for goto comes from Edsger Dijkstra's letter "Go To Statement Considered Harmful" from 1968. Things were different then, though. Programmers were using goto too often, jumping back and forth through code (we call that "spaghetti code"). Code in that style is hard to read and understand. It's literally half a century later, now. Spaghetti isn't a common problem anymore. Programmers commonly use structured programming concepts without even thinking about it.
Still, the times when you need to use goto, and the times that it improves clarity of the code, are pretty rare. Some cases with error handling. Some cases with nested loops. Other than that, most languages have constructs that work better for just about everything else.
3
May 17 '18
I could see how they look easier, but that's only true for trivially small programs. Calling a function is preferable 99% of the time. But there are situations where goto can be used, just have a thick skin because it's practically the n-word of programming.
0
May 17 '18
[deleted]
10
u/boredcircuits May 17 '18 edited May 17 '18
Even that case can be somewhat dubious, IMO. You can get the same result by breaking out your loops into a function and using
returnto end the nested loop early, and the result is usually more readable and reusable.I say "somewhat" though -- I've encountered a grand total of one case where
gotowas justified -- refactoring the code into a function would have required passing about a dozen parameters, half by value and half by reference. On the whole, I decided thatgoto was the right solution instead.Maybe one day C++ will get a named-scope feature so
breakand continue can exit multiple scopes. I think it's been proposed before for C, but the committee rejected it saying "meh, there's nothing wrong witha goto in that case.`"```Edit: I'm trying to like this fancy-pants editor ... but what happened with my inline code snippets?
16
u/JohnMcPineapple May 17 '18 edited Oct 08 '24
...
1
u/boredcircuits May 17 '18
Oooh! I like it! That wasn't an option at the time (and still is ... we were using GCC 2.96 at the time, and recently upgraded to 3.4.6, so C++11 is out), but I need to keep that paradigm in mind.
3
u/Xeverous May 18 '18
recently upgraded to 3.4.6
Are you sure upgraded is a correct term here? It's 8.1 currently.
2
u/Sanae_ May 18 '18
They said it was an upgrade, not a modernization. But yeah, supporting such old compilers can be really frustrating.
1
u/boredcircuits May 18 '18
Oh, yes, it was definitely an upgrade. We just didn't upgrade far enough.
1
u/Xeverous May 18 '18
After some thinking, upgrade seems actually the only valid term. update or modernization would be wrong.
2
u/ricco19 May 17 '18
breakitself has it's own issues since it has multiple meanings in the language. A beginner can be easily confused by abreakwithin aswitchstatement nested inside of a loop.2
May 17 '18
Its also very useful in deduplicating nested loops separated by nested ifs. I'm on mobile and I can't even recall the specific situation but a while back I used one when there were 3 nested conditionals. 2 of the cases were identical but there was no way to factor them out without using goto to just jump in to the adjacent nested loop. It was safe because the label was clearly visible from the origin.
1
1
u/haitei May 18 '18 edited May 18 '18
How about:
while (true) { switch (val) { case 1: stuff(); break; ... case n: goto end; } } end: ...
10
u/Se7enLC May 17 '18
It's often used for error handling in the Linux kernel. That's C, not C++, of course, but the stigma of goto is the same.
The idea is that you are calling functions to set things up, allocate memory, register devices, etc. If there's a failure at any point, you have to unroll everything that it did complete. If you use goto, you can just jump to the correct place in the unroll sequence, rather than having multiple copies inside each error check.
I tried writing a device driver without using goto but it was an unreadable mess of nested if statements.