简体   繁体   English

带增量运算符的Java Switch语句

[英]Java Switch statement with increment operator

int k=0;

switch (k++) {
   case 0: System.out.println("0 is "+k);
}

Output: 输出:

0 is 1 0是1

Why 1? 为什么是1? It's still in switch operator and must be incremented after exit from it. 它仍然在切换操作符中,退出操作后必须递增。

Postfix means it will be incremented after evaluation, NOT after the current block. 后缀表示它将在评估后增加,而不是在当前块之后增加。 In this case it's evaluated, increments k, then branches to the evaluation. 在这种情况下,对它求值,将k递增,然后分支到求值。 Exactly as it should. 完全正确。

The first thing the switch statement does is process the expression (k++) . switch语句所做的第一件事是处理表达式(k++) The result returned is compared to the case value(s). 将返回的结果与案例值进行比较。 But since k++ has already been processed, k has the value of 1 . 但是,由于已经处理了k++ ,因此k的值为1 Since it is a postfix operator, the value returned is the value before it was incremented. 由于它是一个后缀运算符,因此返回的值是递增之前的值。 Thus 0 is returned, though the value after the expression is executed is 1 . 因此,尽管执行表达式后的值为1 ,但返回0

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

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