Boolean in C

In C programming, a Boolean represents a binary state, typically used to indicate whether a condition is true or false. Although C does not have a built-in Boolean type, the concept of Boolean values is implemented using integer values.

Boolean Values in C

Boolean Operations

In C, Boolean operations are performed using relational and logical operators. These operators allow comparisons and logical expressions to evaluate to true or false.

Examples of Boolean in C

Using Integer for Boolean Values

                    
#include <stdio.h>
int main() 
{
  int isTrue = 1;    // 1 represents true
  int isFalse = 0;   // 0 represents false
            
  printf("isTrue: %d\n", isTrue);
  printf("isFalse: %d\n", isFalse);
            
  return 0;
}
                    
                

Output

isTrue: 1
isFalse: 0

Boolean Logic Using Relational Operators

                    
#include <stdio.h>
int main() 
{
  int a = 5, b = 10;
  int result = (a < b);  // Relational operator returns true (1)
            
  printf("Is a less than b? %d\n", result);
            
  return 0;
}
                    
                

Output

Is a less than b? 1

Boolean Logic Using Logical Operators

                    
#include <stdio.h>
int main() 
{
  int a = 5, b = 10;
  int result = (a < b) && (b > 0);  // Logical AND operator
            
  printf("Is a less than b and b greater than 0? %d\n", result);
            
  return 0;
}
                    
                

Output

Is a less than b and b greater than 0? 1

Negating a Boolean Expression

                    
#include <stdio.h>
int main() 
{
  int a = 5, b = 10;
  int result = !(a > b);  // Logical NOT operator
            
  printf("Is a greater than b? %d\n", !(a > b));
            
  return 0;
}
                    
                

Output

Is a greater than b? 0