Booleans in C:

In C, boolean is not a distinct data type like in some other programming languages (e.g., C++, or Python). We use integers to represent boolean values in C. 1 represents true and 0 represents false.

Booleans can store one of the two values:

  • Yes / No
  • True / False
  • 1 / 0

stdbool.h Header:

In modern C (C99 and later), the stdbool.h header file is available introducing a bool type in which there are two constant values;
  • true
  • false

This header file improves the clarity and reduce the chance of errors related to using other data types like integers to represent boolean values. If you are working in the environment that supports C99 or later standards, it is recommended to use stdbool.h library. But if you are working in old environments, you can go with traditional integer convention for boolean values.



booleans.c
#include <stdio.h>
#include <stdbool.h>

int main() {

  // Declaring boolean type variables
  bool isTrue = true;
  bool isFalse = false;
    
  // Printing the values stored in the variables
  printf("%d\n", isTrue);
  printf("%d\n", isFalse);

  return 0;
}

Booleans are used in to apply certain checks. For example, we can say that if age > 18, then print "You are adult". On the other hand if age < 18 then print "You are under age". We will use them in control statements.

booleans.c
#include <stdio.h>
#include <stdbool.h>

int main() {

  // Printing the results directly from the expressions 
  printf("%d\n", 10>5); // It is true
  printf("%d\n", 1>5);   //It is false
  return 0;
}

Booleans and Comparison Operators:

Comparison operators are used to compare the data values stored in two variables. We can use booleans with comparison operators as comparison operators return true or false, we can store the result of comparison operation in a boolean variable.

booleans.c
#include <stdio.h>
#include <stdbool.h>

int main() {

  // Boolean expressions
  bool check1 = (10 == 10);    
  printf("%d\n",check1);

  // Boolean expressions
  bool check2 = (10 < 4);    
  printf("%d\n",check2);
  
  return 0;
}