c++中,bool与int 的区别

菜鸟一枚,为了观察区别,特地运行了下面几个语句

 1 /*阅读程序回答问题,
 2 1.bool类型的false对应数值?true呢?
 3 2.非0整数对应bool型的?0呢? 
 4  */ 
 5 #include<iostream>
 6 #include<cstring>
 7 using namespace std;
 8 int main(){
 9     cout<<(2>1)<<(2==1)<<endl;
10      bool b=1<2;cout<<b<<endl;
11      bool c=3;cout<<c<<endl;
12     bool d=-3;cout<<d<<endl;
13      int e=3;cout<<e<<endl;
14      bool f=1;cout<<sizeof(f)<<endl;
15      if (5) cout<<"5  true"<<endl;
16      if (-5) cout<<"-5  true"<<endl;
17      if (0) cout<<"0 is ?"<<endl;
18      return 0;
19 }
View Code

输出结果:

10

1

1

1

3

1

5 true

-5 true

 收获:bool类型占一个字节,对于任何非0整数都代表true,只有0代表false;

原文地址:https://www.cnblogs.com/ssfzmfy/p/4648912.html