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
- True: A non-zero value, commonly represented by
1
. - False: A zero value, represented by
0
.
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
.
- Relational Operators: Operators such as
==
,!=
,<
,>
, etc. are used to compare values and return a Boolean result. - Logical Operators: Operators such as
&&
(AND),||
(OR), and!
(NOT) are used to combine or negate Boolean expressions.
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
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