Java后缀自增/自减表达式的返回值

Java后缀自增/自减表达式的返回值

今天看到一段代码,描述循环k次

    while(k-- > 0){
        //...
    }

直觉上认为是错的,k--后值变成了k-1,循环应该只能执行k-1次吧。实际这段代码是正确的。在Java8语言规范15.14.3中有以下描述:

The value of the postfix decrement expression is the value of the variable before the new value is stored.

即后缀自减表达式的值为存储新值之前的值,尽管k--之后的k值变成了k-1,但是表达式k--的返回值还是k,所以以上代码可以循环k次。
上述规则对于后缀自增表达式同样适用。
然后顺手查了下前缀自增/自减表达式的返回值,JLS的描述如下:

The value of the prefix increment expression is the value of the variable after the new value is stored.
The value of the prefix decrement expression is the value of the variable after the new value is stored.

所以上述代码如果改成下面这样,就真的只能循环k-1次了

    while(--k > 0){
        //...
    }

猜你喜欢

转载自www.cnblogs.com/filozofio/p/12306177.html