On Goto statement
This mostly applies for C programming where I came across following pattern.
Resources may be anything (memory, lock, file). I find it highly uncomfortable to write these exceptional aborts and prone to resource leaks.
This can be done much more nicely using goto
This is obviously much more readable and safe.
Are there any advantages of the first version?
- You release only what is actually acquired (in the case that even release
of unallocated resource has some costs (e.g.
free(NULL)
)). - You have very strong reluctance to
goto
. This may apply if your code already uses somegoto
s.
Other solutions
- GNU extensions of C language provide option of
variable attribute
cleanup
that allows you to associate a function that’s called when released should be performed. - Use C++ or other languages.