如果声明条件

时间:2013-11-07 18:19:41

标签: c++ if-statement

我无法理解此代码的作用:

#include <iostream>

using namespace std;

int main()
{
    int x = 0, y = 0;
    if (x++ && y++)
        y += 2;
    cout << x + y << endl;
    return 0;
}

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

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

4 个答案:

答案 0 :(得分:6)

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

由于false && expression将为任何表达式产生false,因此无需评估其余表达式。

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

这称为Short-circuit Evaluation

答案 1 :(得分:1)

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

现在你有x=1y=0

结果是1。

答案 2 :(得分:0)

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

之后的结果是x = 1且y = 0;

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

答案 3 :(得分:0)

我建议您查看运算符优先级图表: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;
}
相关问题