Why and when should a goto be used in C / C++? [duplicate]

喜欢而已 提交于 2019-12-02 04:10:58

There is no circumstance under which a goto is strictly necessary: you can always avoid it if you really want to, but to do that for purely idealogical reasons is a mistake.

For example, a friend of mine wrote a wavelet transform function that had (something like) 15 nested loops. In the event of an error in those loops, he had a goto to a cleanup block just before the function's return statement. To achieve the same effect without a goto would have involved setting a flag and testing it at every loop level, which would have made his code far less readable. In these circumstances, goto was the right choice.

The latest MISRA standard now allows gotos.

A good example where gotos make sense is when you have a large routine with a lot of exits points. You can have many return statements (not good) convolute the code with 'structured programming' conditionals (also not good) or a "goto Done; which sends the program to a set of ending statements before returning.

The MISRA standard basically allows gotos for these sort of circumstances. I think 'only downward' is one of their criteria.

The only reason I use a goto is when it is for an error return condition from a function that needs some common cleanup. The target of the goto is near the end of the function and the "normal" return returns before the label.

Andrew Cottrell

Here is an example where only goto will work: https://stackoverflow.com/a/245801/193848

Basically if you have multiple nested for loops, the only way to break out of all the loops from an inner loop is with a goto statement (since unlike some other languages the C break keyword doesn't support a parameter for the number of nesting levels to break out).

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!