首页 > 解决方案 > 为什么带有`cout`的条件被评估为真?

问题描述

为什么带有条件的if语句cout << c << endl被评估为 true。

下面的代码运行没有显示错误。我不明白为什么会这样。

#include <iostream>

using namespace std;

int main()
{
    int c = 0;
    if (cout << c << endl) {
        c++;
    }
    cout << c <<endl;
    return 0;
}

另外,为什么我在那里不需要分号?

标签: c++if-statementconditional-statementscout

解决方案


std::cout不返回true。这是这里operator bool 返回的重载。iostreamcout

bool 运算符返回true,除非最后采用的是eof或操作已导致failbad状态。

现在,为什么不需要分号?因为它是一个表达式而不是一个语句。

就像你使用时一样

while(true)// you don't write while(true;)

推荐阅读