运算符优先级-在Java中,先执行“ +”还是“ ++”?
我在Java中尝试了以下代码
t1 = 5;
t2 = t1 + (++t1);
System.out.println (t2);
我的观点是,由于++的优先级高于+,因此以上内容变为
t2 = t1 + (++t1);
t2 = t1 + 6; // t1 becomes 6 here
t2 = 6 + 6;
t2 = 12;
但是,我得到2的答案11。 有人可以解释吗?
10个解决方案
76 votes
您几乎是正确的,但是您巧妙地误解了优先规则的工作原理。
比较这两种情况:
int t1 = 5;
int t2 = t1 + (++t1);
System.out.println (t2);
t1 = 5;
t2 = (++t1) + t1;
System.out.println (t2);
结果是:
11
12
确实确实要说优先级是在Y之前先评估++,但这并不适用,直到到达表达式的该部分为止。
您的表达形式为++其中Y是Y和++是(++t1)
首先评估左分支,即++。之后,评估右分支,即Y。仅在评估Y时才执行++操作。
优先级规则只说++在Y表达式的“内部”,它们没有说明操作顺序。
Tim B answered 2020-01-07T22:36:57Z
55 votes
您的逻辑很接近,但不太正确。 对于+运算符,评估顺序是从左到右。 t1在二进制运算LHS之前,然后增量在该二进制运算的RHS上。 LHS首先执行。
t2 = t1 + (++t1);
t2 = 5 + 6; // t1 becomes 6 here as a side effect before being read on the RHS
t2 = 11;
可视化为您拥有的树,
+
/ \
t1 ++t1
优先顺序
当两个运算符共享一个操作数时,优先级较高的运算符排在第一位。 例如,将1 + 2 * 3视为1 +(2 * 3),将1 * 2 + 3视为(1 * 2)+ 3,因为乘法的优先级高于加法。
关联性
当两个运算符具有相同的优先级时,将根据表达式的关联性对表达式进行求值。 例如x = y = z = 17被视为x =(y =(z = 17)),而所有三个变量的值都为17,因为=运算符具有从右到左的关联性(并且赋值语句求值 到右侧的值)。 另一方面,由于/运算符具有从左到右的关联性,因此将72/2/3视为(72/2)/ 3。
Chris K answered 2020-01-07T22:37:40Z
15 votes
另一种思维方式是扩展++表达式:
t2 = (++t1) + t1;与放置t1 = t1 + 1相同。
1) t1 = 5;
2) t2 = t1 + (++t1);
3) t2 = t1 + (t1 = t1 + 1),
4) t2 = 5 + (t1 = t1 + 1)
5) t2 = 5 + (t1 = 6)
6) t2 = 5 + 6 = 11
如果您要将顺序反转为t2 = (++t1) + t1;,则表达式将扩展为:
1) t2 = (t1 = t1 + 1) + t1
2) t2 = (t1 = 5 + 1) + t1
3) t2 = (t1 = 6) + t1
4) t2 = 6 + 6 = 12
JWiley answered 2020-01-07T22:38:09Z
5 votes
要为Chris K添加一个点,
关联性是从左到右
所以,
t2 = t1 + (++t1);
t2 = 5 + 6; // first t1 is replaced with 5 and then the next 6
t2 = 11;
subham soni answered 2020-01-07T22:38:37Z
3 votes
从左到右评估了11,因此
t1 + (++t1) // Left side is evaluated to 5, right side evaluated to 6...
5 + (6) // ...and as a side effect t1 becomes 6
结果为11。
icza answered 2020-01-07T22:39:01Z
2 votes
评价从左到右进行。 所以实际上发生了什么
t2 = t1 + (++t1);
t2 = 5 + 6;
t2 = 11;
Ruchira Gayan Ranaweera answered 2020-01-07T22:39:21Z
2 votes
第二行中t1的值为5
t2 = t1 + (++t1)
t2 = 5 + 6; // t1 becomes 6 here
评估顺序是从左到右。
因此,首先将t1评估为5,然后将++t1评估为++t1280,因此结果为11
Rahul Tripathi answered 2020-01-07T22:39:50Z
0 votes
在使用变量x之前执行++ x,并且在使用变量x之后x ++增加x:
x=5;
y=x++;
y is 5;
and x is 6
x=5;
y=++x;
y is 6;
and x is 6
Izu answered 2020-01-07T22:40:10Z
0 votes
t2 = t1 + (++t1);
这相当于
temp = t1 + 1
t2 = t1 + temp;
t1= temp;
mirmdasif answered 2020-01-07T22:40:30Z
0 votes
enter code here
t1 = 5;
t2 = t1 + (++t1);
// it takes 5 for t1 and as it moves further to (++t1), it increments t1 to 6, so it takes 6 for (++t1)
t2 = 5 + 6;
// (++t1) this increments t1 by 1 then return new value. So (++t1)=6
// (t1++) this returns old value n then increments t1 by 1. So (t1++)=5
Harshad Patil answered 2020-01-07T22:40:45Z