Why are variables not local in case statements?

前端 未结 6 1460
暖寄归人
暖寄归人 2020-12-10 14:03

I recently add another menu item to an android java app and was suprised that Eclipse said that variable from the previous case:break were not local (So I\'ve just added a s

6条回答
  •  隐瞒了意图╮
    2020-12-10 14:09

    Others have explained what you should do, and that this is a Java language thing, not an Android specific thing.

    As to why the Java Language is defined this way, I haven't figured an entirely logical reason. The best I can think of is that if each of the case lists of a switch statement implicitly defined a scope, then the following could easily be misread:

    case foo:
       int var = ...
       // note drop through
    case bar:
                                  int var = ...
       var = var + 1;
       break;
    

    At least with the current definition of the scoping, all of the potentially confusing usages result in compilation errors.

    (IMO, it would have been better to eschew case drop-through in switch statements ... just like C# does. But design mistakes like that are much easier to spot in hindsight, and are hard to correct once made.)

提交回复
热议问题