LWN.net Logo

It's not a mistake to ban goto... it's not a mistake to keep it...

It's not a mistake to ban goto... it's not a mistake to keep it...

Posted Feb 10, 2008 11:57 UTC (Sun) by filipjoelsson (subscriber, #2622)
In reply to: It's not a mistake to ban goto... it's not a mistake to keep it... by khim
Parent article: Interview: Mark "Markey" Kretschmann (Not the Gentoo Weekly News)

The last time I saw goto in serious use (where last is defined as most recent instance of
coding - not last time I viewed ancient code), was in some DirectX example code (shipped with
DirectX in ca 1999 - so it is a half way ancient, and it is MS being responsible).

Anyway, the way they used it was to skip to a dtor-like section of a function. Not
particularly elegant, not particularly object oriented, but not outright heresy either -
which, since I thought it _was_ outright heresy confused me.

Ever since, I have been trying to solve it in more elegant ways (using C++). Nested ifs,
functors, exceptions, you name it - it's not very elegant either. Anybody know a better way to
free resources in a C++ function when failing? (I tend to think the nested ifs are the least
evil - but they do eat the line width at an alarming rate.)

EORant ;)


(Log in to post comments)

It's not a mistake to ban goto... it's not a mistake to keep it...

Posted Feb 10, 2008 13:48 UTC (Sun) by nix (subscriber, #2304) [Link]

The Linux kernel uses goto in this manner all the time. It's useful if you 
can't do it by splitting the non-ctor-dtor stuff into a separate function.

freeing resources

Posted Feb 11, 2008 3:26 UTC (Mon) by pflugstad (subscriber, #224) [Link]

Are you looking for RAII?

I use it quite often for things like mutexes, but it can be used in many other situations - any time you hold a resource in a function that must be cleaned up when the function exits, including when throwing an exception.

It's a fairly common design pattern for C++ these days - I think I started seeing it a year or two ago...

freeing resources

Posted Feb 11, 2008 8:19 UTC (Mon) by nix (subscriber, #2304) [Link]

In C++ it's probably two decades old: I know it was landing in published 
textbooks ten years ago.

I didn't see it in C outside the Linux kernel before about 2004.

Copyright © 2012, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds