If-statemenet condition

If-statemenet condition

本文关键字:condition If-statemenet      更新时间:2023-10-16

我很难理解这段代码的作用:

#include <iostream>
using namespace std;
int main()
{
    int x = 0, y = 0;
    if (x++ && y++)
        y += 2;
    cout << x + y << endl;
    return 0;
}

输出为 1 x C++。但我认为应该是2?

为什么?因为在 if 语句的 () 中,我认为应该只检查它是否为真/假,因此它不会增加/减少任何整数。由于默认情况下这是真的,因此它为 2 增加 y?输出应该是 0+2 = 2,但它只输出 1?

if (x++ && y++)不会做y++,因为逻辑和运算符(&&)左侧的条件是false的,因为x++将返回0并将x递增1。

由于false && expression 将为任何表达式生成 false,因此无需计算其余表达式。

因此,您最终会得到 x = 1y = 0 .

这称为短路评估。

++算子具有高优先级,&&算子可以进行短路评估。if (x++ && y++)中发生的事情是,首先它评估x++ 。结果为 0 并递增 x。由于 0 是假的 &&&会短路y++的评估(不会被执行)。此外,if 将计算为 false,并且不会执行y+=2

所以现在你有x=1y=0.

所以结果是 1。

它将首先执行x++,编译器知道因此表达式x++ && y++将为假,并将忽略y++

结果之后 x = 1 和 y = 0;

它与写if(false && do_something())相同,在这种情况下,do_something()永远不会被调用。

我建议你看看运算符优先级表: http://en.cppreference.com/w/cpp/language/operator_precedence

//in a statement, x++ will evaluate x then increment it by 1.
//in a statement, ++x will increment x by 1 then evaluate it.

如果您很难理解它,请尝试以下代码以更好地理解:

#include <iostream>
using namespace std;
int main()
{
    int x = 0, y = 0;
    if (++x && ++y) // in your case, with the previous code, it gives (0 && 0)
    // instead of if statement you can try the following : cout << x++;  then cout << ++x; 
    // and notice the difference
        y += 2;
    cout << x + y << endl;
    return 0;
}