c++ 中 bool 与整型之间的转换

本文详细介绍了C++中bool类型与整型之间的隐式转换规则。当bool类型的变量被赋值为非零整数时,其值会被视为true;而赋值为0时,则被视为false。此外,当整型数值被赋予bool变量时,非零值会转换为true,0则转换为false。文章通过具体示例代码展示了这一转换过程及其在条件判断中的应用。

在c++中bool类型与整型之间存在着隐式转换,bool在存储之后隐式的转换为整型存储,其中true为1,false则为0。如果用整型给bool对象赋值,非零值为true,0则为false。

#include <iostream>

using namespace std;

int main()
{
    bool t = true;
    cout << "t is true: " << t << endl;
    t = false;
    cout << "t is false: " << t << endl;
    t = 10 ;
    if(t)
    {
        cout << "t is true: " << t << endl;
    }
    else
    {
        cout << "t is false: " << t << endl;
    }
    t = -10;
    if(t)
    {
        cout << "t is true: " << t << endl;
    }
    else
    {
        cout << "t is false: " << t << endl;
    }
    t = 0;
    if(t)
    {
        cout << "t is true: " << t << endl;
    }
    else
    {
        cout << "t is false: " << t << endl;
    }
}

程序输出

t is true: 1
t is false: 0
t is true: 1
t is true: 1
t is false: 0

 

转载于:https://my.oschina.net/u/3193939/blog/2966503

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值