C++中if条件中赋值运算符的使用 [英] Use of assignment operators inside if condition in C++

查看:153
本文介绍了C++中if条件中赋值运算符的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在 if 条件中使用赋值运算符或输出函数,为什么将其视为真"布尔值?

If I use assignment operators or output functions inside the if condition, why is it taken as a "true" boolean value?

例如,我做

if(cout << "a"){cout << "c";}

if(int x=7){cout << "c";}

甚至

if(6){cout << "c";}

输出确实,在每种情况下都是c和c和c.但是我们被告知,在 if 条件中,我们必须使用一个表达式,最终计算结果为布尔值,如 1 或 0.

the outputs are indeed, c and c and c in each case. But we were told that, inside the if condition, we have to use an expression that finally evaluates to a boolean value like 1 or 0.

那么我遗漏的信息是什么?

So what is the piece of information I am missing?

推荐答案

在每种情况下,表达式都被转换为 bool.这个 bool 的值在您使用的三种情况下都为真(它可能并不总是为真).

In each case the expression is converted to a bool. The value of this bool is true in the three cases that you use (it may not always be true).

if(cout << "a"){cout << "c";}

在这种情况下,表达式:

In this case the expression:

   cout << "a"

如果找到operator<<(std::ostream&, char const*)定义,你会发现返回值是std::ostream&.所以这将返回对 cout 对象(类型为 std::ostream)的引用.流对象具有布尔转换方法explicit bool(),可用于将对象转换为布尔值.这样做的结果取决于对象的状态(如果它处于坏(失败)状态,它将返回 false).

If find the operator<<(std::ostream&, char const*) definition you will find that the return value is std::ostream&. So this will return a reference to the cout object (of type std::ostream). The stream object has a boolean conversion method explicit bool() which can be used to convert the object to bool. The result of this depends on the state of the object (if it is in a bad (failing) state it will return false).

所以在这里您要检查流上的最后一个操作是否有效.如果是,则打印c".这通常用于输入流以验证用户输入.

So here you are checking that the last operation on the stream worked. If it does then print "c". This is commonly used on input streams to validate user intput.

int val;
if (std::cin >> val) {
    if (std::cout << "A value was correctly read\n") {
        // Add response worked.
    }
    else
    {
        // Something bad happened to std::cout
    }
}

在其他情况下,您使用 int 变量.这些可以隐式转换为 bool.如果该值不为零,则为真(否则为假).

In the other cases you use int variables. These can be implicitly converted to bool. If the value is non zero then it is true (otherwise false).

这篇关于C++中if条件中赋值运算符的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆