在开关中使用“goto"? [英] Use a 'goto' in a switch?

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

问题描述

我看到了一个建议的编码标准,它是 Never use goto unless in a switch statement fall-through.

I've seen a suggested coding standard that reads Never use goto unless in a switch statement fall-through.

我不关注.这个异常"案例究竟是什么样的,可以证明 goto 的合理性?

I don't follow. What exactly would this 'exception' case look like, that justifies a goto?

推荐答案

这个构造在 C# 中是非法的:

This construct is illegal in C#:

switch (variable) {
   case 2: 
       Console.WriteLine("variable is >= 2");
   case 1:
       Console.WriteLine("variable is >= 1");
}

在 C++ 中,如果 variable = 2,它将运行两行.这可能是故意的,但很容易忘记第一个 case 标签末尾的 break;.出于这个原因,他们在 C# 中将其设为非法.要模仿跌倒行为,您必须明确使用 goto 来表达您的意图:

In C++, it would run both lines if variable = 2. It may be intentional but it's too easy to forget break; at the end of the first case label. For this reason, they have made it illegal in C#. To mimic the fall through behavior, you will have to explicitly use goto to express your intention:

switch (variable) {
   case 2: 
       Console.WriteLine("variable is >= 2");
       goto case 1;
   case 1:
       Console.WriteLine("variable is >= 1");
       break;
}

也就是说,有 少数情况 goto 实际上是很好的解决问题.永远不要关闭你的大脑永远不要使用某些东西"规则.如果它是 100% 无用的,那么它一开始就不会存在于语言中.不要使用 goto 是一个指南;这不是法律.

That said, there are a few cases where goto is actually a good solution for the problem. Never shut down your brain with "never use something" rules. If it were 100% useless, it wouldn't have existed in the language in the first place. Don't use goto is a guideline; it's not a law.

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

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