c语言中使用bool
First, understand the bool in C++ programming language. In C++ programming, "bool" is a primitive data type and it can be used directly like other data types. "bool" is a Boolean data type that is used to store two values either true (1) or false (0).
首先,了解C ++编程语言中的bool 。 在C ++编程中, “布尔”是一种原始数据类型,可以像其他数据类型一样直接使用。 “布尔”是布尔数据类型,用于存储两个值,分别为true(1)或false(0)。
C中的布尔类型 (bool type in C)
But in C programming language, a "bool" is defined in stdbool.h header file. Thus, to use a bool type in our program, we must include stdbool.h header files. As a standard feature, a bool variable can store either true (1) or false (0) value.
但是在C编程语言中, stdbool.h头文件中定义了一个“布尔” 。 因此,要在我们的程序中使用布尔类型,我们必须包括stdbool.h头文件。 作为标准功能,布尔变量可以存储true ( 1 )或false ( 0 )值。
Syntax:
句法:
bool variable_name;
Example 1:
范例1:
#include <stdio.h>
#include <stdbool.h>
int main()
{
bool var1 = true;
bool var2 = false;
bool var3 = 1;
bool var4 = 0;
// printing the values
printf("var1: %d\n", var1);
printf("var2: %d\n", var2);
printf("var3: %d\n", var3);
printf("var4: %d\n", var4);
return 0;
}
Output:
输出:
var1: 1
var2: 0
var3: 1
var4: 0
Example 2:
范例2:
#include <stdio.h>
#include <stdbool.h>
int main()
{
bool status = true;
if (status)
printf("It's true...\n");
else
printf("It's false...\n");
status = false;
if (status)
printf("It's true...\n");
else
printf("It's false...\n");
return 0;
}
Output:
输出:
It's true...
It's false...
Note: Any non-zero value will be considered as a true value. Thus, we can assign anything that should return either non-zero or zero.
注意:任何非零值都将被视为真实值。 因此,我们可以分配任何应返回非零或零的值 。
Consider the below example,
考虑下面的示例,
Example 3:
范例3:
#include <stdio.h>
#include <stdbool.h>
int main()
{
bool x = true;
printf("x : %d\n", x);
x = -1;
printf("x : %d\n", x);
x = -123.45f;
printf("x : %d\n", x);
x = "Hello";
printf("x : %d\n", x);
x = 123.456f;
printf("x : %d\n", x);
x = 0;
printf("x : %d\n", x);
x = NULL;
printf("x : %d\n", x);
return 0;
}
Output:
输出:
x : 1
x : 1
x : 1
x : 1
x : 1
x : 0
x : 0
Also read: bool data type in C++
另请参阅: C ++中的bool数据类型
翻译自: https://www.includehelp.com/c/use-of-bool-in-c-language.aspx
c语言中使用bool