C - Booleans
There are many instances in the programming, where a user need a data type which represents True and False values. For this, C has a bool data type, which takes either True or False values.
Boolean Values
A boolean variable is declared with bool keyword and can only take boolean values: True or False values. In the example below, a boolean variable called MyBoolVal is declared to accept only boolean values.
#include <stdio.h> #include <stdbool.h> int main (){ bool MyBoolVal = true; printf("%i\n", MyBoolVal); //returns 1 (true) MyBoolVal = false; printf("%i\n", MyBoolVal); //returns 0 (false) return 0; }
The output of the above code will be:
1 0
Boolean Expressions
A boolean expression in C is an expression which returns boolean values: 1 (true) or 0 (false) values. In the example below, comparison operator is used in the boolean expression which returns 1 when left operand is greater than right operand else returns 0.
#include <stdio.h> int main (){ int x = 10; int y = 25; printf("%i\n", (x > y)); //returns 0 (false) return 0; }
The output of the above code will be:
0
A logical operator can be used to combine two or more conditions to make complex boolean expression like && operator is used to combine conditions which returns 1 (true) if all conditions are true else returns 0 (false). See the example below:
#include <stdio.h> int main (){ int x = 10; printf("%i\n", (x > 0 && x < 25)); //returns 1 (true) return 0; }
The output of the above code will be:
1