r/cprogramming • u/LilBalls-BigNipples • Jan 09 '26
Is this use of goto acceptable?
I know goto is generally pretty frowned upon, but there is one use case that *always* tempts me:
If, in the beginning of my main, I have several libraries to initialize, that will be cleaned up at the very end of execution. As I'm going through each API, each failure condition adds another cleanup call. I typically make a "cleanup" label (with a pointer to check or a bool for the init status of each library) and jump to it on a failure instead. That way, the failure check for each library remains consistent, and i can rearrange them without much thought. Thoughts?
48
u/tstanisl Jan 09 '26
The
gotois a tool like every other. Maybe a bit sharper than other tools thus one must be a bit more carreful.15
u/Savings-Snow-80 Jan 09 '26
Yes, this is of course acceptable and also (widely) used in the Linux™ source code.
You can also use goto to make state machines/parsers, like so: https://codeberg.org/Phosphenius/yoctofetch/src/branch/main/src/os_release.c
8
u/Timberfist Jan 09 '26
Sometimes, a
gotois exactly the tool you need.In the case you describe, initialisation code is often messy. Maybe group it into a single initialisation function so that the doing functions can focus on the job at hand.
11
u/MisterHarvest Jan 09 '26 edited Jan 09 '26
To quote Captain Barbossa, “... the Code is more what you'd call guidelines than actual rules.” The real rule, for me, on
gotoand similar constructs is: Never use it to replace a control structure if that control structure can do what you need done (edited to add for clarity) in a concise and clear fashion.One example: I have a piece of code that takes a data item, and passes it to a long (but fixed) set of functions, each one of which has a chance to process it. Once a function has processed it, processing is done on that particular data item, so we need to break out of the flow. A
gotois not insane there, especially given that C doesn't have native exceptions. (In the end, that bit of code was replaced by a list of function pointers and aforloop, but the example remains.)6
u/foo1138 Jan 09 '26
The cleanup case you describe is a totally legit reason to use goto. I would even argue that goto is the best practice there. People are somewhat "brainwashed" about goto. When I was learning C programming, I also was told that goto is bad and mustn't be used and I beleived it for a long time and also repeated this nonsense to others. Like others already pointed out here, in the Linux kernel they use goto excessively for exactly such cleanup cases, and it makes the code sooo much easier to read.
It is believed that the "brainwashing" about goto originated from an article from Edsger Dijkstra who later regretted it, because of the discussions it caused: https://stackoverflow.com/questions/46586/goto-still-considered-harmful?utm_source=chatgpt.com
3
u/Liquid_Magic Jan 09 '26
I use it in abhorrent ways in my ChiCLI program for the Commodore 64 using cc65. I replaced it with something that does things “the right way” but switched it back because it resulted in way smaller code. In general I get about 47kb of program size to work with in this case. It’s terrible - classic example of how not to use goto - but results in smaller code. What can I tell yeah: it works!
3
u/konacurrents Jan 10 '26
Wow this thread just went crazy. Every comment is saying Goto is just another tool. Or 60 years ago Wirth or Bacher said Goto harmful .. get with the 2026 times .. Goto is just fine.
Wrong. Now have a nice day. 👌
2
u/I__be_Steve Jan 09 '26
I would say the most important thing isn't following random rules of thumb, it's making sure your code is readable and maintainable, and control structures are almost always a better option for that, hence the rule of thumb "don't use goto".
If using goto or any other controversial feature makes your code more readable and maintainable, then I would say it'd be foolish not to use it, but that's rarely the case.
In this case, the use of goto sounds clean, concise, and readable, and I can't think of an equivalent way to do this with control structures, so I say go for it, goto sounds like the right tool here :)
2
u/Traveling-Techie Jan 09 '26
I wrote a lot of code in BASIC and tuned a lot of other people’s code in FORTRAN. The big issue was always readability. Many times I printed source on fan-fold and marked it up with fluorescent highlighters.
2
u/Tcshaw91 Jan 09 '26
That's exactly how I use it. Declare all pointers to resources in beginning of function (c89 was on to something), set them all to null. Set up cleanup section at the end where it checks each pointer and deallocates if its not null. Anywhere in the function if something fails, "go-to cleanup;".
It's basically like defer for C. Super helpful.
2
u/qalmakka Jan 10 '26
In general I find the jumping forward is often fine. The real issues generally apply to jumping backwards, which is bad and should be avoided
2
u/Wooden-Engineer-8098 Jan 10 '26
No. Use raii instead
3
u/SmokeMuch7356 Jan 09 '26
That's a reasonable use case. So's breaking out of a deeply nested loop (as long as you're careful about cleaning up any partially allocated resources).
Here are my rules for using
goto:if,for,while, etc.) with agoto;gotowhere an existing control structure would work;2
u/HashDefTrueFalse Jan 09 '26
Yes. Just use it sparingly and only where necessary. Try to jump only short distances and be careful about jumping near where you initialise variables.
The cleanup example is the classic use case and totally acceptable in my book. I much prefer it over convoluted logic.
2
u/Ashamed-Subject-8573 Jan 09 '26
The reason “Goto is considered harmful” has to do with well structured code.
Well structured code flows so that you can pick out random lines and know how the code got there.
This correlates directly with less bugs, according to some research.
Goto breaks that.
It definitely has good uses however
2
u/tharold Jan 10 '26
One nice feature of goto that I don't see mentioned, is that statement labels have a native documenting function (like other symbol names) that control structures do not have. No need to add a comment!
1
u/TheTrueXenose Jan 09 '26
For my project I use it, but in my work it's against the style people follow.
So it depends.
1
u/t4r3k_ Jan 10 '26
Would help to have a code snippet to go with the explanation.
1
u/UnmappedStack Jan 10 '26
For the most part I dislike using it but it's great for cleanup in error handling.
1
u/WorriedTumbleweed289 Jan 10 '26
Do not use goto to create loops. There are other tools for that.
Use for cleanup after error conditions before end of functions.
Can also be used to break out of multiple loops since a break statement can only break out of one at a time.
1
u/Conscious_Support176 Jan 12 '26
Yes.
This is a thing in C because C doesn’t have the RAII tools that C++ gives you.
As with other uses of goto, the problem is that you are using it to manually wire up a control flow that the language itself doesn’t give you. This means you need to take extreme care not to mess it up, and everyone who comes after you needs to read your code carefully to ensure the same thing.
I believe gcc added RAII extensions to C. Would be nice if RAII found its way into c proper.
1
u/LavenderDay3544 Jan 12 '26
Use the standard library function
atexit()instead to register those calls as exit hooks instead of usinggotofor this particular case. That's the right tool for you want to do.Everyone telling you to use
gotofor this doesn't have the faintest clue of how to use the C standard library properly.1
u/sol_hsa Jan 09 '26
I've even found completely justifiable use for longjmp. Would I use it if some other solution is available? No.
1
u/dcpugalaxy Jan 10 '26
Goto is frowned upon by people that are stupid. They are copycatting something they heard a long time ago from other people that also didn't understand it.
1
u/EatingSolidBricks Jan 10 '26 edited Jan 10 '26
People ho talk shit about goto have no idea what yue fuck they're doing
The hole argument is a fallacy, appeal to authority
Even worse when daddy disktra wrote the thing we was talking about BASIC, i don't think C was a thing when he wrote it.
The whole shithole is perpertraed by out of touch academic shills
1
u/Key_River7180 Jan 10 '26
I don't think
gotois harmful at all, it is a very nice way to cleanup stuff without repeating stuff. It's just a nice tool C gives you. Many projects use (e.g.: all suckless software, Linux, etc.). I recommend you read this: jorenar.com/blog/gotophobia-harmful0
u/[deleted] Jan 10 '26
[deleted] — view deleted comment