例子源于c++ primer
bool b=10; // b is true
bool b=-10;// b is true
bool b=0.0;// b is false
int i=10.2;// i is 10 truncated
int j=-10.2;//j is -10
undigned char c=-1; //assuming 8-bits char, c has value 255 255=-1%256
signed char c2=256; //asuuming 8-bits char, the value of c2 is undefined
unsigned int u=10;int i=-10;
cout<<u+i<<endl;// -10 converted to unsigned int first and then add to u, value is 2^32-10+10
cout<<u-40<<endl;//
当写for循环依照从大到小的顺序从10递减输出到0时,如果使用unsigned会出问题
for(unsigned int i=10;i>=0;--i) //因为是unsigned int --i不可能小于0,死循环
cout<<i<<endl;
一种解决方式是用while
unsigned u=11;
while(u>0) //0在undigned int 内 可以判断
{--u;
cout<<u<<endl;
}
参照while思路也可以写出for
for(unsigned int i=11;i>0;)
{
--i;
cout<<i<<endl;
}
//test
bool b=-0.0;
if(b)
cout<<"b is true"<<endl;
else
cout<<"b is false"<<endl;
bool a=0e1;
if(a)
cout<<"a is true"<<endl;
else
cout<<"a is false"<<endl;
int i=-10.2;
cout<<"i is "<<i<<endl;
unsigned int u=10,u2=40;
int t=40;
long long temp=1;
int times=32;
while(times>0)
{
temp*=2;
--times;
}
cout<<"2^32 is "<<temp<<endl;
cout<<"u10-i40 "<<u-t<<endl;
cout<<"u10-u40 "<<u-u2<<endl;
cout<<"-40-u10 "<<-40-u<<endl;
结果:
b is false
a is false
i is -10
2^32 is 4294967296
u10-i40 4294967266
u10-u40 4294967266
-40-u10 4294967246
总结:
1. 如果非bool值赋给bool,如果转换为0(0.0,-0.0,0)则为false,否则是true
2. 如果负数赋给无符号的数,相当于对2^n取余数,n类型的位数决定,char 8 int 32
3. 如果将超过范围的数赋值给带符号的数,结果不确定 比如 int i=2^32; char ch=256;
4. 如果将带符号数与不带符号数混在一起,结果会转换为不带符号数 比如 -40-u10 本来为-50 世纪为2^32-50