c语言case可以用or吗,java-OR操作符在switch-case中?

What are the backgrounds for a switch-case to not accept this operator?

因为情况需要恒定表达式作为其值.而且由于||表达式不是编译时常数,不允许.

开关标签应具有以下语法:

SwitchLabel:

case ConstantExpression :

case EnumConstantName :

default :

在引擎盖下:

Compilation of switch statements uses the tableswitch and lookupswitch instructions. The tableswitch instruction is used when the cases of the switch can be efficiently represented as indices into a table of target offsets. The default target of the switch is used if the value of the expression of the switch falls outside the range of valid indices.

因此,对于由表开关使用的标签作为目标偏移表的索引,在编译时应该知道该值.只有当case值是一个常量表达式时才有可能.和||表达式将在运行时进行评估,该值仅在当时可用.

从相同的JVM部分,以下switch-case:

switch (i) {

case 0: return 0;

case 1: return 1;

case 2: return 2;

default: return -1;

}

编译为:

0 iload_1 // Push local variable 1 (argument i)

1 tableswitch 0 to 2: // Valid indices are 0 through 2 (NOTICE This instruction?)

0: 28 // If i is 0, continue at 28

1: 30 // If i is 1, continue at 30

2: 32 // If i is 2, continue at 32

default:34 // Otherwise, continue at 34

28 iconst_0 // i was 0; push int constant 0...

29 ireturn // ...and return it

30 iconst_1 // i was 1; push int constant 1...

31 ireturn // ...and return it

32 iconst_2 // i was 2; push int constant 2...

33 ireturn // ...and return it

34 iconst_m1 // otherwise push int constant -1...

35 ireturn // ...and return it

因此,如果case值不是常量表达式,编译器将无法使用tableswitch指令将其索引到指令表指针中.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值