if 语句中的 C++ 逻辑条件

C++ logical conditions inside if statements

int a = 2;

if((a = a-3 && --a ) || a--) 
    cout<<a<<endl;

我的疑问是,(a = a-3 && --a) 会使 a = -1 因为 a-3 = -1。左边评估什么?如果编译器确实转到 OR 的右侧,它是从左侧获取 a 的原始值(即 2)还是 a 的修改值 此代码 1 的输出如何?幕后发生了什么?是不是只执行了if语句的一侧?

它首先检查这个:

a-3 && --a

a-3-1 并且不等于零所以结果是 (true)

--a 不为零且结果为 1 (true) 所以 a=truetrue1 所以 a=1;

编译器不检查第二部分并转到下一行

所以它打印 1 输出

( a = a-3 && --a) would make a = -1 because a-3 = -1.

您错过了此处的操作顺序,其中 && 在赋值之前计算。 (赋值几乎是最后求值的东西,当它用在条件之外时这是有意义的。)a-3 确实是 -1,但那个值没有赋给 a。相反,它是 && 的左侧,它的计算结果为 true,因为它是在布尔上下文中使用的。接下来评估 && 的右侧,将 a 减少为 1 并评估为 1。与左侧一样,它被转换为布尔值 (true),导致表达式 a-3 && --a 的计算结果为 true.

因此您的作业归结为 a = truetrue 转换为 1,因为 aint

What does the left side evaluate to?

我猜你是说 && 的左边?该表达式 (a-3) 的计算结果为 true 作为布尔值。

And if the compiler does go to the right side of OR [...]

它不会,因为 || 布尔值短路。 (不过,用户定义的 operator|| 不会短路。)左侧的计算结果为 1(分配给 a 的值),它在 a 中转换为 true布尔上下文。当 || 的左侧计算为 true 时,右侧不计算。

How is the output for this code 1?

当您将它分配给 a 时,这就是 true 转换的结果。

What is happening under the hood?

(a =  a-3 &&  --a ) || a--
(a =  2-3 &&  --a ) || a--
(a =   -1 &&  --a ) || a--
(a = true &&  --a ) || a--
(a = true &&   1  ) || a--
(a = true && true ) || a--
(a =     true     ) || a--
(a =       1      ) || a--
(        1        ) || a--
(      true       ) || a--
           true

Is it like only one side of the if statement is executed?

我不明白 if 语句的“一面”是什么。可能你的意思是“有条件的”而不是“声明”?无论如何,以上内容可能已经回答了您的问题。

要获得您似乎一直期待的结果,请添加括号以覆盖通常的 operator precedence:

if(( (a = a-3) && --a ) || a--)
//   ^       ^