Hacker News new | ask | show | jobs
by monocasa 1925 days ago
I'd like to see the use of goto.

There's two 'allowed' uses in C that are common and represent good code even today. goto error cleanup stubs, and goto in virtual machine dispatch loops.

The size of the codebase doesn't really matter for those cases; they're largely considered the idiomatic way to go about the problems they're trying to solve.

2 comments

The error cleanup role is handled in a number of other languages (Ada, VHDL, Perl) by letting the programmer name a block and having a statement that terminates that block or (for a loop) goes to the next iteration, even if this terminates multiple loops. The effect is similar to the C goto way of doing that, but it's more controlled and easy for compilers to deal with.
Oh, for sure, other languages have different idiomatic constructs that don't require such a heavy hammer as goto to achieve s similar effect.

Even in C, if you're writing Microsoft only code, seh is probably a better mechanism than goto error.

I'd argue that the defer statement in go (and the surprising side effects of it, like that it's function instead of block scope like you might otherwise expect) ultimately come from trying to wrap this idiom in a construct that's better supported by the language.

My point though is that in relatively standard, portable C, there are valid, idiomatic use cases of goto, and it's not quite so easy to say 'eww goto' in those very specific circumstances.

I skimmed some Linux code the other day and noticed that goto is used for more than those two situations. Maybe just cruft...?

Search for retry: or handle_itb: in https://github.com/torvalds/linux/blob/master/fs/ext4/resize...

Or fixleft: or copy: in https://github.com/torvalds/linux/blob/d158fc7f36a25e19791d2...

Yeah, the retry piece is a bit more controversial. Some people think that it's cleaner for code that's probably already nesting loops, but I tend to break it apart in different ways. That one I generally don't push too hard in review, but require more tests to shore up confidence.

And frankly, the fix_left style code you see just isn't modern idiomatic C, IMO. In a code review I'd have them either combo of write a block comment explaining why it's necessary to be weird and a lot of test cases for when someone inevitably tries to rewrite it, or just rewrite it in the first place.

Some of the areas of the Linux kernel aren't exactly known for being the best written C (unfortunate as that is) and you're seeing some of that.