简体   繁体   English

开关案例陈述中的分号

[英]semicolon in fall through of switch case statement

Is there any significance to adding a semicolon in the case statement that is part of a fall-through ? 在附带声明中添加分号是否有任何意义? I see that the fall-through works as expected and guess the semicolon is interpreted as an empty statement. 我看到掉线效果符合预期,并且猜测分号被解释为空语句。 But are there pros/cons to having the semicolon ? 但是使用分号是否有利弊? Is there a certain best practice that is recommended ? 有推荐的某种最佳做法吗? In the javascript example below, see the semicolon in the first case statement. 在下面的JavaScript示例中,请参阅第一个case语句中的分号。

    switch(a) {
        case 2:;
        case 3: alert('hello'); break;
        default: alert('default hello');
    }

I am also interested in knowing about the best practices related to the above in C, C++ and Java. 我也想了解与上述C,C ++和Java有关的最佳实践。 I also saw some documentation that C# throws a compilation error if a case statement part of a fall-through has a statement. 我还看到一些文档,如果掉线事件中的case语句包含一条语句,C#会引发编译错误。 Will an empty statement like the above trigger an error in C#? 像上面的空语句会在C#中触发错误吗?

No, it does not make any difference. 不,没有任何区别。

I recommend you not to use it since it makes the code less clear, in my opinion. 我建议您不要使用它,因为我认为它会使代码不太清晰。

In C# it's an error though. 在C#中,这是一个错误。 D does not allow ; D不允许; as an empty statement too, you have to use {} . 同样作为空语句,也必须使用{}

; does nothing for you in C, C++, and Java. 在C,C ++和Java中对您没有任何帮助。 If you don't need it, don't use it. 如果您不需要它,请不要使用它。 But do throw future readers of your code a bone if you are implementing Duff's Device or a variant and leave them "fall through" or "no break" comments. 但是,如果要实现Duff的Device或变体,请不要让将来的代码阅读者大吃一惊,而要让他们“掉线”或“不间断”注释。

In C# 在C#中

switch(a) {
    case 2:;
    case 3: Console.WriteLine("hello"); break;
    default: Console.WriteLine("default hello");
}

prevents cases 2 and 3 executing the same code by interrupting the little bit of fall through C# does allow. 通过中断C#允许的少量跌落来防止情况2和3执行相同的代码。

switch(a) {
    case 2:
    case 3: Console.WriteLine("hello"); break;
    default: Console.WriteLine("default hello"); break;
}

Would be valid with cases 2 and 3 executing the same code. 在案例2和案例3执行相同代码时将是有效的。

best practice 最佳实践

Is usually not to use an empty statement. 通常是不使用空语句。

Will an empty statement like the above trigger an error in C#? 像上面的空语句会在C#中触发错误吗?

Yes. 是。

Syntactically it's the same 语法上是一样的

It's bound to confuse someone though so I'd recommend against using it 它一定会使人困惑,所以我建议不要使用它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM