【发布时间】:2013-03-07 20:32:44
【问题描述】:
再次受到-5 问题的启发!
我阅读了@Quartermeister 的[this comment] 并感到惊讶!
那么为什么会编译
switch(1) {
case 2:
}
但事实并非如此。
int i;
switch(i=1) {
case 2: // Control cannot fall through from one case label ('case 2:') to another
}
不是这个
switch(2) {
case 2: // Control cannot fall through from one case label ('case 2:') to another
}
更新:
-5 问题变成了-3。
【问题讨论】:
-
有可能编译器可以优化出第一个,但不能删除第二个,因为赋值。
-
我的猜测是
1是编译时已知的常量表达式,让编译器优化整个开关,而i=1是非常量表达式(尽管编译器也知道产生一个特定的值)所以编译器试图保持开关。 -
它与:
int i=1; switch(i) { case 2: // Control cannot fall through from one case label ('case 1:') to another }有什么不同,我认为这是显而易见的...... -
@evanmcdonnal:是的,它是允许的。
switch (i = 1){case 1: Console.WriteLine("foo"); break;}编译、运行和输出“foo”。 -
由于您似乎对 switch 语句感兴趣,您可能想阅读以下内容:blogs.msdn.com/b/ericlippert/archive/2009/08/13/…
标签: c# switch-statement unreachable-code