Использование bool в C
Prerequisite: Bool Data Type in C++
The C99 standard for C language supports bool variables. Unlike C++, where no header file is needed to use bool, a header file “stdbool.h” must be included to use bool in C. If we save the below program as .c, it will not compile, but if we save it as .cpp, it will work fine.
C
int main() { bool arr[2] = { true , false }; return 0; } |
If we include the header file “stdbool.h” in the above program, it will work fine as a C program.
C
#include <stdbool.h> int main() { bool arr[2] = { true , false }; return 0; } |
Есть еще один способ сделать это, используя функцию enum на языке C. Вы можете создать bool, используя enum. Одно перечисление будет создано как bool, затем элементы перечисления будут иметь значения True и False соответственно. Значение false будет в первой позиции, поэтому оно будет содержать 0, а true будет во второй позиции, поэтому оно получит значение 1.
Below is the implementation of the above idea:
C
// C implementation of the above idea #include <stdio.h> // Declaration of enum typedef enum { F, T } boolean; int main() { boolean bool1, bool2; bool1 = F; if (bool1 == F) { printf ( "bool1 is false
" ); } else { printf ( "bool1 is true
" ); } bool2 = 2; if (bool2 == F) { printf ( "bool2 is false
" ); } else { printf ( "bool2 is true
" ); } } |
bool1 is false bool2 is true