c 语言bool 类型数据
In C++ programming language, to deal with the Boolean values – C++ added the feature of the bool data type. A bool variable stores either true (1) or false (0) values.
在C ++编程语言中,为了处理布尔值– C ++添加了bool数据类型的功能 。 布尔变量存储true ( 1 )或false ( 0 )值。
Note that, In C++, true and false are the inbuilt keywords and they represent 1 and 0 respectively.
请注意,在C ++中, true和false是内置关键字,它们分别表示1和0。
So, whenever we need to work with such variables in which we have to store only two values i.e. the variable to hold status like, ON/OFF, YES/NO, TRUE/FALSE, etc we can use bool type variable.
因此,每当需要使用这样的变量时,我们只需要存储两个值即可,即要保持状态的变量,例如ON / OFF,YES / NO,TRUE / FALSE等,我们可以使用bool类型变量 。
Syntax:
句法:
bool variable_name;
Example 1:
范例1:
#include <iostream>
using namespace std;
int main()
{
bool var1 = true;
bool var2 = false;
bool var3 = 1;
bool var4 = 0;
//printing the values
cout << "var1 : " << var1 << endl;
cout << "var2 : " << var2 << endl;
cout << "var3 : " << var3 << endl;
cout << "var4 : " << var4 << endl;
return 0;
}
Output:
输出:
var1 : 1
var2 : 0
var3 : 1
var4 : 0
Example 2:
范例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;
}
Output:
输出:
It's true...
It's false...
Note: Any non-zero value considers as true and zero considers as false.
注意:任何非零值均视为true , 零则视为false 。
Example 3:
范例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;
}
Output:
输出:
x : 1
x : 1
x : 1
x : 1
x : 1
x : 0
x : 0
Also read: Use of bool in C language
另请阅读: 在C语言中使用bool
翻译自: https://www.includehelp.com/cpp-tutorial/bool-data-type-in-cpp.aspx
c 语言bool 类型数据