开发者

What are the acceptable uses of goto? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Examples of good gotos in C or C++

Wh开发者_如何转开发at uses of the goto statement do you consider acceptable? I am discussing some coding guidelines for C embedded work, and wondering if there are cases where goto is the cleanest way to do things.


For C, I find it useful to use goto for a common exit point in some functions. If you need to release resources before returning, it's nice to do retval = -ERROR; goto fn_exit; instead of trying to break out of multiple layers of for/while loops.

Some would argue that it isn't necessary in well designed code -- when you reach a point where using goto is attractive, you should be breaking the function up into multiple sub-functions. Maybe that's true in some cases, but if you have to pass multiple variables in, or pass pointers to variables so a sub-function can update those values, I feel like you've added unnecessary complications.

Here's a recent SO question on using goto for error management. I'm sure that browsing the goto tag will get you even more answers.


I found that there are quite a few places where goto might simplify the logic. My rule is that no 2 goto's overlap each other and that the goto and its label are 'close'; usually, no more than 30 lines apart.

Usually, when I have a complex condition that I have to check many things, a goto might help:

if ( condition1 && cond2 )
  if ( checkFile( file ) )
    goto DONE;
else
  if ( condition3 )
    goto DONE;

handleError();
return 0;

DONE:
...do something...
return 1;


My personal opinion is that there are NO acceptable uses of the goto statement in a modern programming language.

"GOTO Statement Considered Harmful", by the late Edsger W. Dijkstra, does a good job of covering the issue. That paper should be required reading for every software developer on the planet.

It is worth noting that the Gypsy language, from Don Good's group at UT Austin in the late 1970s, did not have a goto.

It is worth noting that Ichbiah et al only included a goto in Ada because the DoD required it, explicitly, in so many words in the requirements specification. I remember reading that Ichbiah and his team deliberately made the goto target label syntax as ugly as they could, to make the labels stick out like sore thumbs, and discourage use of the goto.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜