C ++中的bool数据类型
在C++编程语言中,为了处理布尔值-C++添加了bool数据类型的功能。布尔变量存储true(1)或false值。
请注意,在C++中,true和false是内置关键字,它们分别表示1和0。
因此,每当需要使用这样的变量时,我们只需要存储两个值即可,即要保持状态的变量,如ON/OFF,YES/NO,TRUE/FALSE等,我们可以使用bool类型变量。
语法:
bool variable_name;
范例1:
#include <iostream> using namespace std; int main(){ bool var1 = true; bool var2 = false; bool var3 = 1; bool var4 = 0; //打印值 cout << "//var1: " << var1 << endl; cout << "//var2: " << var2 << endl; cout << "//var3: " << var3 << endl; cout << "//var4: " << var4 << endl; return 0; }
输出:
//var1: 1 //var2: 0 //var3: 1 //var4: 0
范例2:
#include <iostream> using namespace std; int main(){ bool status = true; if (status) cout << "It's true..." << endl; else cout << "It's false..." << endl; status = false; if (status) cout << "It's true..." << endl; else cout << "It's false..." << endl; return 0; }
输出:
It's true... It's false...
注意:任何非零值均视为true,零则视为false。
范例3:
#include <iostream> using namespace std; int main(){ bool x = true; cout << "//x: " << x << endl; x = -1; cout << "//x: " << x << endl; x = -123.45f; cout << "//x: " << x << endl; x = "Hello"; cout << "//x: " << x << endl; x = 123.456f; cout << "//x: " << x << endl; x = 0; cout << "//x: " << x << endl; x = NULL; cout << "//x: " << x << endl; return 0; }
输出:
//x: 1 //x: 1 //x: 1 //x: 1 //x: 1 //x: 0 //x: 0
另请阅读:在C语言中使用bool