Too many people seem to think that "goto" in C is the worst thing you could do. It's an abomination, never use it! (Not something I've seen here per se, just generally around)

Break out of a loop inside a loop without using goto, and make it look pretty. Seriously, I don't think it can be done, and goto just makes it so clean!

  • 3
    Go-to is not wrong but your use case indeed
  • 4
    Encounterd this today, actually. Fixed it by using a boolean to keep track of the state and used it to break out of the loop.

    Really though, having nested loops is a code smell, and usually means there's logic to be extracted. One nested is alright, any more is pushing it.
  • 1
    @schil227 semi agreed. But it really helps when dealing with multiple dimensional arrays.

    Or the case I've seen the most. You are dealing with a two dimensional arrays in an infinite loop. That's a while true, and then two for loops for a depth of 3. Getting all the way out, and halting is just not pretty without goto.

    I've admittedly done the Boolean tracking, but it just feels cleaner to define a label at the end of the nesting and just goto that.
  • 2
    can't you just encapsulate the loop in a function and return when you are done?
  • 2
    @deadPix3l fair enough - I suppose the next best thing would be to extract the nested loops to a function and return out with the relevant details, but, details.
  • 1
    @vhoyer @schil227 I guess you could, but what if you need a clean up step like freeing some pointers or a final adjustment to the value or good forbid another loop for whatever reason!

    My point is yea it's possible to avoid goto entirely and many people do, but I believe there are small niche cases where it is the only clean, acceptable answer.
  • 1
    Using goto for ressource cleanup is a common pattern in the Linux kernel, see also: https://eli.thegreenplace.net/2009/...

    Readable and easy to follow code is more important than some dogma.
Your Job Suck?
Get a Better Job
Add Comment