在C++中,有些情况下表达式的值被自动转换为true或false,比如int,double,char等类型,本文给出一些测试,比如0.0和'\0'会被自动转换成false。
1 #include <iostream>
2
3 #define T "true"
4 #define F "false"
5
6 using namespace std;
7
8 int main() {
9 int intt = -2;
10 int intf = 0;
11 double dt = 0.1;
12 double df = .0;
13 char ct = 'a';
14 char cf = '0';
15 char cf0 = '\0';
16 char cfn = '\n';
17 char cfr = '\r';
18 char cfb = '\b';
19 string st = "2";
20 string sf = "0";
21 bool bt = true;
22 bool bf = false;
23
24 cout << "-2 == " << (intt ? T : F) << '\n';
25 cout << "0 == " << (intf ? T : F) << '\n';
26 cout << "0.1 == " << (dt ? T : F) << '\n';
27 cout << "0.0 == " << (df ? T : F) << '\n';
28 cout << "\'a\' == " << (ct ? T : F) << '\n';
29 cout << "\'0\' == " << (cf ? T : F) << '\n';
30 cout << "\'\\0\' == " << (cf0 ? T : F) << '\n';
31 cout << "\'\\n\' == " << (cfn ? T : F) << '\n';
32 cout << "\'\\r\' == " << (cfr ? T : F) << '\n';
33 cout << "\'\\b\' == " << (cfb ? T : F) << '\n';
34 cout << "\"2\" == " << (st ? T : F) << '\n'; //error: could not convert ‘st’ to ‘bool’
35 cout << "\"0\" == " << (sf ? T : F) << '\n'; //error: could not convert ‘sf’ to ‘bool’
36 cout << "true == " << (bt ? T : F) << '\n';
37 cout << "false == " << (bf ? T : F) << '\n';
38
39 return 0;
40 }
41
g++ 4.4.5编译,报错,因为在第34和35行中,string无法被自动转换成bool类型。把第34和35行注释掉,再编译,通过。以下是结果:
-2 == true
0 == false
0.1 == true
0.0 == false
'a' == true
'0' == true
'\0' == false
'\n' == true
'\r' == true
'\b' == true
true == true
false == false
可以看出,double的0.0和字符型中的'\0'被自动转换成了false,注意,'0'被自动转换成了true。