使用"goto"语句不好吗? [英] Is using a 'goto' statement bad?

查看:147
本文介绍了使用"goto"语句不好吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在研究了如何突破次级循环之后

After doing some reseach on how to break through a secondary loop

while (true) { // Main Loop
   for (int I = 0; I < 15; I++) { // Secondary loop
       // Do Something
       break; // Break main loop?
   }
}

大多数人建议调用"goto"功能
看下面的例子:

most people recommended to call the 'goto' function
Looking as the following example:

while (true) { // Main Loop
   for (int I = 0; I < 15; I++) { // Secondary Loop
       // Do Something
       goto ContinueOn; // Breaks the main loop
   }
}
ContinueOn:

但是;我经常听到'goto'声明是不好的做法.下图完美地说明了我的观点:

However; I have often heard that the 'goto' statement is bad practice. The picture below is perfectly illustrating my point:

  • goto语句到底有多糟糕?为什么?
  • 是否有比使用'goto'语句更有效的方法来打破主循环?
  • How bad is the goto statement really, and why?
  • Is there a more effective way to break the main loop than using the 'goto' statement?

推荐答案

goto语句到底有多糟糕?为什么?

How bad is the goto statement really, and why?

这取决于实际情况.我不记得任何时候我发现它使代码比重构更易读.这也取决于您对可读性的个人看法-从其他答案中可以明显看出,有些人比其他人更不喜欢它. (有意思的是,它广泛地用于生成的代码中-C#5中的所有异步/等待代码实际上都是基于很多getos的.)

It depends on the exact situation. I can't remember any time where I found it made the code more readable than refactoring. It also depends on your personal view of readability - some people dislike it more than others, as is clear from the other answers. (As a point of interest, it's widely used in generated code - all of the async/await code in C# 5 is based on effectively a lot of gotos).

问题在于,goto倾向于被使用 tend 的情况是无论如何重构都可以帮助事情的情况-而goto坚持的解决方案变得越来越难以遵循代码变得更加复杂.

The problem is that situations where goto tends to be used tend to be the kind of situations where refactoring aids things anyway - whereas goto sticks with a solution which becomes harder to follow as the code gets more complicated.

有没有比使用"goto"语句更有效的方法来打破主循环?

Is there a more effective way to break the main loop than using the 'goto' statement?

绝对.将您的方法提取到一个单独的函数中:

Absolutely. Extract your method out into a separate function:

while (ProcessValues(...))
{
    // Body left deliberately empty
}

...

private bool ProcessValues()
{
   for (int i = 0; i < 15; i++)
   {
       // Do something
       return false;
   }
   return true;
}

相对于引入额外的局部变量来跟踪我完成了",我通常更喜欢这样做-尽管当然可以.

I generally prefer doing this over introducing an extra local variable to keep track of "have I finished" - although that will work to, of course.

这篇关于使用"goto"语句不好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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