C ++引入了一种名为bool的新型数据类型,它代表Boolean。引入此数据类型以支持true或false值,这意味着我们可以存储true或false值。我们还可以将0存储为false或1存储为true。
bool数据类型在内存中仅占用1字节。
语法
bool variable_name=boolean_value;
bool variable_name=0/1;
布尔文字是对还是错,这是C ++编程中添加的两个关键字。这里true代表1,false代表0。
如果尝试打印true和false值,则值分别为1和0,让我们考虑以下语句:
cout<<"value of true is: " <<true <<endl; cout<<"value of false is: "<<false<<endl;
输出结果
value of true is: 1 value of false is: 0
这是一个示例,其中我们在变量marital_status中分配false,true和0
#include <iostream>
using namespace std;
int main(){
	//分配false-
	bool marital_status=false;
	
	cout<<"Type1..."<<endl;
	if(marital_status==false)
	    cout<<"You're unmarried"<<endl;
	else
	    cout<<"You're married"<<endl;
	//分配true-
	marital_status=true;
	cout<<"Type2..."<<endl;
	if(marital_status==false)
	    cout<<"You're unmarried"<<endl;
	else
	    cout<<"You're married"<<endl;
	//现在将0分配为false-
	marital_status=0;
	cout<<"Type3..."<<endl;
	if(marital_status==false)
	    cout<<"You're unmarried"<<endl;
	else
	    cout<<"You're married"<<endl;	
	
	return 0;	
}输出结果
Type1... You're unmarried Type2... You're married Type3... You're unmarried