C Boolean

C language supports a data type called _Bool or bool which is used to represent boolean values. The boolean data type can only have two values: 0 (false) or 1 (true).

In C, boolean values are primarily used in conditional statements to test the truthfulness of an expression.

Here is an example demonstrating the declaration and assignment of boolean variables in C:

1#include <stdio.h> 2#include <stdbool.h> 3 4int main() { 5 bool flag1 = true; 6 bool flag2 = false; 7 8 printf("flag1: %d\n", flag1); 9 printf("flag2: %d\n", flag2); 10 return 0; 11}

In this example, two boolean variables flag1 and flag2 are declared and assigned values true and false respectively. The values of these variables are then printed using the printf function. The %d format specifier is used to print integer values, as boolean values in C are stored as integers 0 (false) or 1 (true).

The output of this code will be:

1flag1: 1 2flag2: 0

Check bool variable in if statement

1#include <stdio.h> 2#include <stdbool.h> 3 4int main() { 5 bool flag = true; 6 if (flag == true) { 7 printf("flag is true\n"); 8 } else { 9 printf("flag is false\n"); 10 } 11 return 0; 12}

In this example, flag is declared as a boolean variable with a value of true. The if statement tests the truthfulness of flag and if it is true, it prints "flag is true", otherwise, it prints "flag is false".

It's worth noting that in C, true and false are not reserved keywords, but _Bool or bool are defined in the stdbool.h header file. So to use boolean values in C, it is necessary to include this header file.