为什么不同的 case 条件体不在不同的范围内? [英] Why are different case condition bodies not in different scope?

查看:38
本文介绍了为什么不同的 case 条件体不在不同的范围内?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不同的案例主体不会自动在它们自己的范围内?例如,如果我要这样做:

Why are different case bodies not automatically in their own scope? For example, if I were to do this:

switch(condition) {
  case CONDITION_ONE:
    int account = 27373;
  case CONDITION_TWO:
    // account var not needed here
  case CONDITION_THREE:
    // account var not needed here
  case CONDITION_FOUR:
    int account = 90384;
}

编译器会抱怨局部变量重新定义.我知道我可以这样做:

the compiler would complain about local variable redefinitions. I understand I could do this:

switch(condition) {
  case CONDITION_ONE: {
    int account = 27373;
  }
  case CONDITION_TWO: {
    // account var not needed here
  }
  case CONDITION_THREE: {
    // account var not needed here
  }
  case CONDITION_FOUR: {
    int account = 90384;
  }
}

在要执行的每组语句周围放置一个块,以将每个 account 变量放在其自己的范围内.但为什么语言不为我做这件事?

to put a block around each set of statements to be executed to put each account variable in its own scope. But why doesn't the language do this for me?

您为什么要在 CONDITION_ONE 的主体中声明一个局部变量,然后在 CONDITION_TWO 的主体中使用它?这似乎是一个可怕的想法,应该明确禁止,而不是默许.

Why would you ever want to declare a local variable in CONDITION_ONE's body and then use it in CONDITION_TWO's? This seems like a TERRIBLE idea which should be explicitly banned, not implicitly permitted.

推荐答案

那会与语言的其余部分不一致.

That would be inconsistent with the rest of the language.

事实上,范围总是由块决定.这种一致性使 Java 更易于阅读和维护.

As it is, scope is always determined by blocks. That sort of consistency makes Java easier to read and maintain.

这篇关于为什么不同的 case 条件体不在不同的范围内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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