变量在Java中的赋值优先级

huangapple go评论75阅读模式
英文:

Assignment priority of variables in java

问题

我有一个代码片段示例

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

请问有人可以解释一下为什么在这种情况下 `i3` 的值会被初始化为5吗?我原以为 `(i2 = i1)` 之后的 `i2` 会是2。然后 `i2 + i2` 应该是4。
英文:

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? I thought that i2 after (i2 = i1) will be 2. And i2 + i2 will be 4

答案1

得分: 3

你正在犯将运算符优先级与操作数评估顺序混淆的常见错误。

优先级仅影响表达式的结构(即含义)。由于您使用了显式括号,对于i2 + (i2 = i1),没有真正的疑问 - 它绝对不能表示(i2 + i2) = i1

然而,在Java中,操作数的评估始终是从左到右。因此i2 + (i2 = i1) 的含义是:

  1. 获取i2的值,称为'tmp1'
  2. 获取i2的地址,称为'tmp2'
  3. 获取i1的值
  4. 将该值的副本存储在地址'tmp2'处
  5. 将手中的值与'tmp1'的值相加
  6. 这是表达式的结果

这个序列仅用于教学,我并不是说这是编译器生成的实际目标代码。但这是如何理解您将获得的结果的方式。

然而,在实际应用中,您不应编写将赋值与对变量使用先前值相结合的代码。如果我在进行代码审查,我会建议您重新表达。

英文:

You are making the common error of confusing operator priority with order of evaluation of operands.

Priority affects the structure (i.e., 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.

HOWEVER, in Java, evaluation of operands is always left-to-right. So `i2 + (i2 = i1)' means:

  1. Take value of i2, call it 'tmp1'
  2. Take address of i2, call it 'tmp2'
  3. Take value of i1
  4. Store a copy of that value at address 'tmp2'
  5. Add the value in hand to the value of '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.

huangapple
  • 本文由 发表于 2020年9月1日 06:58:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/63679235.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定