简体   繁体   English

java中变量的赋值优先级

[英]Assignment priority of variables in java

I have a code snippet example我有一个代码片段示例

int i1 = 2;
int i2 = 3;
int i3 = i2 + (i2 = i1); 

Please can anyone explain to me why i3 will be initialized with 5 in this case?请谁能向我解释为什么在这种情况下i3将被初始化为 5? I thought that i2 after (i2 = i1) will be 2. And i2 + i2 will be 4我认为, i2(i2 = i1)将2.和i2 + i2将为4

You are making the common error of confusing operator priority with order of evaluation of operands.您正在犯将运算符优先级与操作数的评估顺序混淆的常见错误。

Priority affects the structure (ie, meaning) of the expression only.优先级仅影响表达式的结构(即含义)。 Since you use explicit parentheses, there's no real doubt in i2 + (i2 = i1) -- it can't possibly mean (i2 + i2) = i1 .由于您使用显式括号,因此在i2 + (i2 = i1)毫无疑问 - 它不可能意味着(i2 + i2) = i1

HOWEVER, in Java, evaluation of operands is always left-to-right .然而,在 Java 中,操作数的计算总是从左到右 So `i2 + (i2 = i1)' means:所以‘i2 + (i2 = i1)’意味着:

  1. Take value of i2, call it 'tmp1'取 i2 的值,称之为“tmp1”
  2. Take address of i2, call it 'tmp2'取 i2 的地址,称之为 'tmp2'
  3. Take value of i1取 i1 的值
  4. Store a copy of that value at address 'tmp2'在地址“tmp2”处存储该值的副本
  5. Add the value in hand to the value of 'tmp1'将手头的值与 'tmp1' 的值相加
  6. which is the result of the expression这是表达式的结果

This sequence is didactic only, I do not mean this is the actual object code produced by the compiler.这个序列只是说教,我并不是说这是编译器生成的实际目标代码。 But it is how to understand what result you'll get.但它是如何理解你会得到什么结果。

In practice, though, you don't want to be writing code that's combining assignments to a variable and using the prior value of the variable.但是,在实践中,您不希望编写将赋值组合到变量并使用变量的先验值的代码。 If I were doing the code review, I'd advise you to reformulate.如果我在做代码审查,我会建议你重新制定。

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

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