c++ - 为什么带有`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;
}
另外,为什么我在那里不需要分号?
解决方案
std::cout
不返回true
。这是这里operator bool
返回的重载。iostream
cout
bool 运算符返回true
,除非最后采用的是eof
或操作已导致fail
或bad
状态。
现在,为什么不需要分号?因为它是一个表达式而不是一个语句。
就像你使用时一样
while(true)// you don't write while(true;)
推荐阅读
- ruby - 使用 Ruby 为 Unicode 值生成十六进制代码点
- ios - Ionic 3 HTTP 请求在 ios 上不起作用,但在 android 上起作用?
- sql - ORACLE SQL:组合 2 行 2 个单独的选择查询
- erlang - 为什么 Erlang/OTP gen_server 回调模块必须提供 handle_cast 函数?
- php - OSError:[Errno 2] 没有这样的文件或目录:php shell_exec [AWS-Lambda] 内的 [python 脚本]
- html - Total Validator 找不到跳过链接
- c++ - 可以使用带有 const 引用或复制参数的函数的函数指针
- azure - 将 Azure AD MFA 与 MIM 和本地应用程序结合使用
- php - 在选择下拉列表中显示月份及其编号 - laravel
- linux - Docker 卸载 Sawtooth 市场