【发布时间】:2017-07-11 08:18:45
【问题描述】:
根据优先级表,一元后缀递增和递减运算符的优先级高于关系运算符,那么为什么在这样的表达式 (x++ >=10) 中,关系运算符先求值,然后变量递增?
【问题讨论】:
-
它并不完全是重复的,但请查看这个:stackoverflow.com/questions/35390737/…
标签: java increment operator-precedence
根据优先级表,一元后缀递增和递减运算符的优先级高于关系运算符,那么为什么在这样的表达式 (x++ >=10) 中,关系运算符先求值,然后变量递增?
【问题讨论】:
标签: java increment operator-precedence
运算符不首先被评估。顺序是:
x++) - 结果是 x 的原始值,然后增加 x 10) - 结果是 10下面的代码可以证明这一点:
public class Test {
static int x = 9;
public static void main(String[] args) {
boolean result = x++ >= showXAndReturn10();
System.out.println(result); // False
}
private static int showXAndReturn10() {
System.out.println(x); // 10
return 10;
}
}
这会打印出10 然后是false,因为在评估RHS 时x 已经 增加了...但是>= 运算符仍在评估9 >= 10因为表达式x++ 的结果是x 的原始 值,而不是增加的值。
如果您希望结果在之后递增,请改用++x。
【讨论】:
在增量之前不计算关系运算符。
首先计算关系运算符(x++ 和10)的操作数。
但是,x++ 的计算增加了x,但返回了x 的原始值,因此即使已经发生了增加,传递给关系运算符的值也是x 的原始值。
【讨论】:
你的结论不正确。 x++ 是先评估的,只是它的值是为后缀增量操作定义的增量之前的 x 值。
【讨论】:
因为这就是 "++, --" 的工作方式。如果它在变量之后,则使用旧值,然后值增加,如果它在变量之前,则首先发生增量,然后使用新值。 所以,如果你想在增加它的值之后再检查它之前使用变量,然后使用 (++x >= 10),或者在没有引用的情况下增加它然后检查它,就像这样:
int x = 0;
x++;
if(x >= 10) {...}
【讨论】:
无论您如何将一元运算符放在表达式中,下表总结了它的用法。
+----------+-------------------+------------+-----------------------------------------------------------------------------------+
| Operator | Name | Expression | Description |
+----------+-------------------+------------+-----------------------------------------------------------------------------------+
| ++ | prefix increment | ++a | Increment "a" by 1, then use the new value of "a" in the residing expression. |
| ++ | postfix increment | a++ | Use the current value of "a" in the residing expression, then increment "a" by 1. |
| -- | prefix decrement | --b | Decrement "b" by 1, then use the new value of "b" in the residing expression. |
| -- | postfix decrement | b-- | Use the current value of "b" in the residing expression, then decrement "b" by 1. |
+----------+-------------------+------------+-----------------------------------------------------------------------------------+
public class UnaryOperators {
public static void main(String args[]) {
int n;
// postfix unary operators
n = 10;
System.out.println(n); // prints 10
System.out.println(n++); // prints 10, then increment by 1
System.out.println(n); // prints 11
n = 10;
System.out.println(n); // prints 10
System.out.println(n--); // prints 10, then decrement by 1
System.out.println(n); // prints 9
// prefix unary operators
n = 10;
System.out.println(n); // prints 10
System.out.println(++n); // increment by 1, then prints 11
System.out.println(n); // prints 11
n = 10;
System.out.println(n); // prints 10
System.out.println(--n); // decrement by 1, then prints 9
System.out.println(n); // prints 9
}
}
【讨论】: