如何使得“num”在这个布尔值中发生变化,以便它变成6?

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

How does "num" become changed in this boolean so that it becomes 6?

问题

int num = 5;
if (num != 5 & num++ != 6 | (num = num--) == 6)
    System.out.println("true " + num);
else
    System.out.println("false " + num);

这段代码的输出是:"true, 6"。我需要帮助理解 num 如何通过布尔语句计算出数字 6。

英文:
int num = 5;
if (num != 5 & num++ != 6 | (num = num--) == 6)
System.out.println("true " + num);
else
System.out.println("false " + num);

The output of this code is "true, 6". I need help on understanding how num evaluates to the number 6 through the boolean statement.

答案1

得分: 1

正如Colin在这里所提到的,实际上在这里发生了很多事情!

首先,让我来看看if条件中表达式的一半;

    num != 5 & num++ != 6 

这段代码首先评估num是否不等于5,即false。

接下来,评估num是否不等于6,即true(后增量)。

然后,评估按位与运算符,即false & true

使得这半个表达式的结果为false

接着,将num的值递增,从5变为6

现在来看剩余的表达式;

    (num = num--) == 6

这部分表达式首先评估括号内的内容。

在这里,num--会将num减少并返回旧值,而当前值为6。
然后,将这个值再次赋给num,这是一个经典的后增量/赋值混淆(详见https://stackoverflow.com/a/24564625/11226302,有详细的解释)。

其次,评估num是否等于6,即true

这就是num在表达式结束时被评估为6的方式。

这使得表达式的第二部分为true

在此之后,|位包含或运算符起作用,评估整个表达式,即

    false | true

使其变为true

英文:

As Colin here has put, there is actually a lot going on here!

Let me take one half of the expression in the if condition first;

    num != 5 & num++ != 6 

Now what this does is first evaluates that num is not equal to 5 ,ie, false

Second, evaluates that num is not equal to 6 ,ie, true (postincrement)

Third, evaluates for the bitwise AND operator ,ie, false & true
<br>
Making the result false for this half of the expression

Forth, increments the value of num ,ie, from 5 to 6
<br>
<br>
<br>
Now for the remaining expression;

    (num = num--) == 6

This part of the expression first evaluates the bracket.

Here num-- decrements num and returns the old value which is 6 currently.
Then this value is assigned to num again it's a classic postincrement/assignment confusion (Do see https://stackoverflow.com/a/24564625/11226302 for detailed explanation)

Second, it evaluates if num is equal to 6 ,ie, true

That is how the value of num evaluates to 6 at the end of the expression.

This makes the second half of the expression true

<br>
<br>
<br>

After this the | bitwise inclusive OR operator takes precedence and evaluates the overall expression, which is

    false | true

Making it true.

huangapple
  • 本文由 发表于 2020年8月21日 03:45:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/63512182.html
匿名

发表评论

匿名网友

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

确定