clinuxloopslinux-kernelgoto

Why do some kernel programmers use goto instead of simple while loops?


When I learned C, teacher told me all day long: "Don't use goto, that's a bad habit, it's ugly, it's dangerous!" and so on.

Why then, do some kernel programmers use goto, for example in this function, where it could be replaced with a simple

while(condition) {} 

or

do {} while(condition);

I can't understand that. Is it better in some cases to use goto instead of while/do-while? And if so, why?


Solution

  • In the case of this example, I suspect it was about retrofitting SMP support into code that was originally written in a non-SMP-safe way. Adding a goto again; path is a lot simpler and less invasive than restructuring the function.

    I can't say I like this style much, but I also think it's misguided to avoid goto for ideological reasons. One special case of goto usage (different from this example) is where goto is only used to move forward in a function, never backwards. This class of usages never results in loop constructs arising out of goto, and it's almost always the simplest, clearest way to implement the needed behavior (which is usually cleaning up and returning on error).