它是有史以来最好使用'转到',支持循环和功能的语言?如果是这样,为什么? [英] Is it ever advantageous to use 'goto' in a language that supports loops and functions? If so, why?

查看:125
本文介绍了它是有史以来最好使用'转到',支持循环和功能的语言?如果是这样,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我早就把IM pression下的转到不应该尽可能使用。而细读libav codeC(这是写在C)有一天,我发现它的多种用途。它是以往任何时候都有利之处在于支持循环和功能使用的语言转到?如果是这样,为什么?

I've long been under the impression that goto should never be used if possible. While perusing libavcodec (which is written in C) the other day, I noticed multiple uses of it. Is it ever advantageous to use goto in a language that supports loops and functions? If so, why?

推荐答案

有使用转到语句的几个原因,我所知道的(有些人说这个话):

There are a few reasons for using the "goto" statement that I'm aware of (some have spoken to this already):

干净利落退出函数

通常在一个函数,你可以分配资源并需要退出在多个地方。程序员可以通过将资源清理code。在函数结束简化其code和功能的所有的出口点会转到清理标签。这样一来,您不必在函数的每一个出口写清理code。

Often in a function, you may allocate resources and need to exit in multiple places. Programmers can simplify their code by putting the resource cleanup code at the end of the function, and all "exit points" of the function would goto the cleanup label. This way, you don't have to write cleanup code at every "exit point" of the function.

退出嵌套循环

如果你是在一个嵌套循环,需要摆脱的所有的循环,一个goto可以让这个更清洁和更简单的比break语句和if-检查。

If you're in a nested loop and need to break out of all loops, a goto can make this much cleaner and simpler than break statements and if-checks.

低级别的性能改进

这是只有在法律约束的关键code有效,但goto语句非常快速执行,并通过函数移动时可以给你一个刺激。这是一个双刃剑,但是,因为编译器通常不能优化code包含的goto。

This is only valid in perf-critical code, but goto statements execute very quickly and can give you a boost when moving through a function. This is a double-edged sword, however, because a compiler typically cannot optimize code that contains gotos.

请注意,在所有这些例子中,goto方法被限制在一个单一的功能的范围。

Note that in all these examples, gotos are restricted to the scope of a single function.

这篇关于它是有史以来最好使用'转到',支持循环和功能的语言?如果是这样,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆