C++中if条件中赋值运算符的使用

编程入门 行业动态 更新时间:2024-10-17 11:30:23
本文介绍了C++中if条件中赋值运算符的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

如果我在 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屋!

更多推荐

[db:关键词]

本文发布于:2023-05-01 13:11:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1410110.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:赋值   运算符   条件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!